pystring

package
v2.3.3 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 10, 2024 License: MIT Imports: 11 Imported by: 0

README

PyString

An attempt to get as similar behavior as possible that exists in python.

Source reference: https://docs.python.org/3/library/string.html#string.Formatter

Dialects

Occasionally, Python implementations may vary between versions necessitating specification of the Python version to achieve direct parity. The aim is to outline required feature flags necessary to attain compatibility in "dialects".

Out of scope

Python 2.X (string % dict) compatibility. 3.X is enough.

TODO

Format() - Support locale aware formatting

  • The 'z' option coerces negative zero floating-point values to positive zero after rounding to the format precision. This option is only valid for floating-point presentation types.
  • The ',' option signals the use of a comma for a thousands separator. For a locale aware separator, use the 'n' integer presentation type instead
  • The '_' option signals the use of an underscore for a thousands separator for floating point presentation types and for integer presentation type 'd'. For integer presentation types 'b', 'o', 'x', and 'X', underscores will be inserted every 4 digits. For other presentation types, specifying this option is an error.

Other features

Str Functions

Low Priority

Documentation

Index

Constants

This section is empty.

Variables

View Source
var DefaultDialect = NewDialect(3.11)

there has been multiples changes in python in regards to how format specifiers are handled to enable all possible formats we captures these changes feature flags which can be opted in our out into.

View Source
var DialectPython3_0 = NewDialect(3.0)
View Source
var DialectPython3_10 = NewDialect(3.10)
View Source
var DialectPython3_11 = NewDialect(3.11)

Functions

func CapWords

func CapWords(s string) string

Split the argument into words using str.split(), capitalize each word using str.capitalize(), and join the capitalized words using str.join(). If the optional second argument sep is absent or None, runs of whitespace characters are replaced by a single space and leading and trailing whitespace are removed, otherwise sep is used to split and join the words.

func Capitalize

func Capitalize(s string) string

Return a copy of the string with its first character capitalized and the rest lowercased.

func Casefold

func Casefold(s string) string

Return a casefolded copy of the string. Casefolded strings may be used for caseless matching.

Casefolding is similar to lowercasing but more aggressive because it is intended to remove all case distinctions in a string. For example, the German lowercase letter 'ß' is equivalent to "ss". Since it is already lowercase, lower() would do nothing to 'ß'; casefold() converts it to "ss".

The casefolding algorithm is described in section 3.13 ‘Default Case Folding’ of the Unicode Standard.

New in version 3.3.

func Center

func Center(s string, width int, fillchar rune) string

Return centered in a string of length width. Padding is done using the specified fillchar (default is an ASCII space). The original string is returned if width is less than or equal to len(s).

func Count

func Count(s, subStr string, start, end *int) int

Return the number of non-overlapping occurrences of substring sub in the range ) {} //[start, end]. Optional arguments start and end are interpreted as in slice notation.

If sub is empty, returns the number of empty strings between characters which is the length of the string plus one.

func Encode

func Encode(str, encoding, errors string) ([]byte, error)

Return the string encoded to bytes. encoding defaults to 'utf-8'; see Standard Encodings for possible values. errors controls how encoding errors are handled. If 'strict' (the default), a UnicodeError exception is raised. Other possible values are 'ignore', 'replace', 'xmlcharrefreplace', 'backslashreplace' and any other name registered via codecs.register_error(). See Error Handlers for details. For performance reasons, the value of errors is not checked for validity unless an encoding error actually occurs, Python Development Mode is enabled or a debug build is used.

func EndsWith

func EndsWith(s, subStr string, start, end *int) bool

Return True if the string ends with the specified suffix, otherwise return False. suffix can also be a tuple of suffixes to look for. With optional start, test beginning at that position. With optional end, stop comparing at that position.

func ExpandTabs

func ExpandTabs(s string, tabSize *int) string

Return a copy of the string where all tab characters are replaced by one or more spaces, depending on the current column and the given tab size. Tab positions occur every tabsize characters (default is 8, giving tab positions at columns 0, 8, 16 and so on). To expand the string, the current column is set to zero and the string is examined character by character. If the character is a tab (\t), one or more space characters are inserted in the result until the current column is equal to the next tab position. (The tab character itself is not copied.) If the character is a newline (\n) or return (\r), it is copied and the current column is reset to zero. Any other character is copied unchanged and the current column is incremented by one regardless of how the character is represented when printed.

>>> >>> '01\t012\t0123\t01234'.expandtabs(){} '01 012 0123 01234' >>> '01\t012\t0123\t01234'.expandtabs(4){} '01 012 0123 01234'

func Find

func Find(s, subStr string, start, end *int) int

Return True if the string ends with the specified suffix, otherwise return False. suffix can also be a tuple of suffixes to look for. With optional start, test beginning at that position. With optional end, stop comparing at that position.

func Format

func Format(s string, vargs []any, kwarg map[string]any) (string, error)

Perform a string formatting operation. The string on which this method is called can contain literal text or replacement fields delimited by braces {}. Each replacement field contains either the numeric index of a positional argument, or the name of a keyword argument. Returns a copy of the string where each replacement field is replaced with the string value of the corresponding argument.

>>> >>> "The sum of 1 + 2 is {0}".format(1+2){} 'The sum of 1 + 2 is 3'

See Format String Syntax for a description of the various formatting options that can be specified in format strings.

func FormatMap

func FormatMap(s string, vargs []any, kwarg map[string]any) (string, error)

Alias for Format

func FormatMapWithDialect

func FormatMapWithDialect(d Dialect, s string, vargs []any, kwarg map[string]any) (string, error)

Alias for FormatWithDialect

func FormatWithDialect

func FormatWithDialect(d Dialect, s string, vargs []any, kwarg map[string]any) (string, error)

Perform a string formatting operation. The string on which this method is called can contain literal text or replacement fields delimited by braces {}. Each replacement field contains either the numeric index of a positional argument, or the name of a keyword argument. Returns a copy of the string where each replacement field is replaced with the string value of the corresponding argument.

>>> >>> "The sum of 1 + 2 is {0}".format(1+2){} 'The sum of 1 + 2 is 3'

See Format String Syntax for a description of the various formatting options that can be specified in format strings.

Changes in python versions are captured by different dialects.

func Idx

func Idx(s string, start, end *int) (string, error)

Idx replicates indexing behavior in python. As such it supports negative indexing and don't crash on out of bound indexes.

func IndexFirstNonDigit

func IndexFirstNonDigit(s string) int

func IsASCII

func IsASCII(s string) bool

Return True if all characters in the string are decimal characters and there is at least one character, False otherwise. Decimal characters are those that can be used to form numbers in base 10, e.g. U+0660, ARABIC-INDIC DIGIT ZERO. Formally a decimal character is a character in the Unicode General Category “Nd”.

func IsAlnum

func IsAlnum(s string) bool

Return True if all characters in the string are alphanumeric and there is at least one character, False otherwise.

func IsAlpha

func IsAlpha(s string) bool

Return True if all characters in the string are alphabetic and there is at least one character, False otherwise. Alphabetic characters are those characters defined in the Unicode character database as “Letter”, i.e., those with general category property being one of “Lm”, “Lt”, “Lu”, “Ll”, or “Lo”. Note that this is different from the Alphabetic property defined in the section 4.10 ‘Letters, Alphabetic, and Ideographic’ of the Unicode Standard.

func IsDecimal

func IsDecimal(s string) bool

Return True if all characters in the string are decimal characters and there is at least one character, False otherwise. Decimal characters are those that can be used to form numbers in base 10, e.g. U+0660, ARABIC-INDIC DIGIT ZERO. Formally a decimal character is a character in the Unicode General Category “Nd”.

func IsDigit

func IsDigit(s string) bool

Return True if all characters in the string are digits and there is at least one character, False otherwise. Digits include decimal characters and digits that need special handling, such as the compatibility superscript digits. This covers digits which cannot be used to form numbers in base 10, like the Kharosthi numbers. Formally, a digit is a character that has the property value Numeric_Type=Digit or Numeric_Type=Decimal.

func IsLower

func IsLower(s string) bool

Return True if all characters in the string are digits and there is at least one character, False otherwise. Digits include decimal characters and digits that need special handling, such as the compatibility superscript digits. This covers digits which cannot be used to form numbers in base 10, like the Kharosthi numbers. Formally, a digit is a character that has the property value Numeric_Type=Digit or Numeric_Type=Decimal.

func IsNumeric

func IsNumeric(s string) bool

Return True if all characters in the string are digits and there is at least one character, False otherwise. Digits include decimal characters and digits that need special handling, such as the compatibility superscript digits. This covers digits which cannot be used to form numbers in base 10, like the Kharosthi numbers. Formally, a digit is a character that has the property value Numeric_Type=Digit or Numeric_Type=Decimal.

func IsPrintable

func IsPrintable(s string) bool

Return True if all characters in the string are printable or the string is empty, False otherwise. Nonprintable characters are those characters defined in the Unicode character database as “Other” or “Separator”, excepting the ASCII space (0x20) which is considered printable. (Note that printable characters in this context are those which should not be escaped when repr() is invoked on a string. It has no bearing on the handling of strings written to sys.stdout or sys.stderr.)

func IsSpace

func IsSpace(s string) bool

Return True if there are only whitespace characters in the string and there is at least one character, False otherwise.

A character is whitespace if in the Unicode character database (see unicodedata), either its general category is Zs (“Separator, space”), or its bidirectional class is one of WS, B, or S.

func IsTitle

func IsTitle(s string) bool

Return True if the string is a titlecased string and there is at least one character, for example uppercase characters may only follow uncased characters and lowercase characters only cased ones. Return False otherwise.

func IsUpper

func IsUpper(s string) bool

Return True if all cased characters ) {} //[4] in the string are uppercase and there is at least one cased character, False otherwise.

>>> >>> 'BANANA'.isupper(){} True >>> 'banana'.isupper(){} False >>> 'baNana'.isupper(){} False >>> ' '.isupper(){} False

func JoinString

func JoinString[T ~string](s T, it []T) string

Return a string which is the concatenation of the strings in iterable. A TypeError will be raised if there are any non-string values in iterable, including bytes objects. The separator between elements is the string providing this method.

func JoinStringer

func JoinStringer[T fmt.Stringer](s string, it []T) string

func LJust

func LJust(s string, width int, fillchar rune) string

Return the string left justified in a string of length width. Padding is done using the specified fillchar (default is an ASCII space). The original string is returned if width is less than or equal to len(s).

func LStrip

func LStrip(s string, cutset string) string

Return a copy of the string with leading characters removed. The chars argument is a string specifying the set of characters to be removed. If omitted or None, the chars argument defaults to removing whitespace. The chars argument is not a prefix; rather, all combinations of its values are stripped:

>>> >>> ' spacious '.lstrip(){} 'spacious ' >>> 'www.example.com'.lstrip('cmowz.'){} 'example.com'

See func removeprefix() for a method that will remove a single prefix string rather than all of a set of characters. For example:

>>> >>> 'Arthur: three!'.lstrip('Arthur: '){} 'ee!' >>> 'Arthur: three!'.removeprefix('Arthur: '){} 'three!'

func Lower

func Lower(s string) string

Return a copy of the string with all the cased characters ) {} //[4] converted to lowercase.

The lowercasing algorithm used is described in section 3.13 ‘Default Case Folding’ of the Unicode Standard.

func NewScanner

func NewScanner(s string, d Dialect) *pyStringScanner

func Partition

func Partition(s string, delim string) (string, string, string)

Split the string at the first occurrence of sep, and return a 3-tuple containing the part before the separator, the separator itself, and the part after the separator. If the separator is not found, return a 3-tuple containing the string itself, followed by two empty strings.

func RFind

func RFind(s string, substr string, start, end *int) int

Return the highest index in the string where substring sub is found, such that sub is contained within s) {} //[start:end]. Optional arguments start and end are interpreted as in slice notation. Return -1 on failure.

func RJust

func RJust(s string, width int, fillchar rune) string

Return the string right justified in a string of length width. Padding is done using the specified fillchar (default is an ASCII space). The original string is returned if width is less than or equal to len(s).

func RPartition

func RPartition(s string, delim string) (string, string, string)

Split the string at the last occurrence of sep, and return a 3-tuple containing the part before the separator, the separator itself, and the part after the separator. If the separator is not found, return a 3-tuple containing two empty strings, followed by the string itself.

func RSplit

func RSplit(s string, delim string, maxSplit int) []string

Return a list of the words in the string, using sep as the delimiter string. If maxsplit is given, at most maxsplit splits are done, the rightmost ones. If sep is not specified or None, any whitespace string is a separator. Except for splitting from the right, rsplit() behaves like split() which is described in detail below.

func RStrip

func RStrip(s string, cutset string) string

Return a copy of the string with trailing characters removed. The chars argument is a string specifying the set of characters to be removed. If omitted or None, the chars argument defaults to removing whitespace. The chars argument is not a suffix; rather, all combinations of its values are stripped:

>>> >>> ' spacious '.rstrip(){} ' spacious' >>> 'mississippi'.rstrip('ipz'){} 'mississ'

See func (pys PyString)removesuffix() for a method that will remove a single suffix string rather than all of a set of characters. For example:

>>> >>> 'Monty Python'.rstrip(' Python'){} 'M' >>> 'Monty Python'.removesuffix(' Python'){} 'Monty'

func RemovePrefix

func RemovePrefix(s string, prefix string) string

If the string starts with the prefix string, return string) {} [len(prefix):]. Otherwise, return a copy of the original string:

>>> >>> 'TestHook'.removeprefix('Test'){} 'Hook' >>> 'BaseTestCase'.removeprefix('Test'){} 'BaseTestCase'

New in version 3.9.

func RemoveSuffix

func RemoveSuffix(s string, prefix string) string

If the string ends with the suffix string and that suffix is not empty, return string) {} //[:-len(suffix)]. Otherwise, return a copy of the original string:

>>> >>> 'MiscTests'.removesuffix('Tests'){} 'Misc' >>> 'TmpDirMixin'.removesuffix('Tests'){} 'TmpDirMixin'

New in version 3.9.

func Replace

func Replace(s string, old, new string, count int) string

Return a copy of the string with all occurrences of substring old replaced by new. If the optional argument count is given, only the first count occurrences are replaced.

func Split

func Split(s string, delim string, maxSplit int) []string

Return a list of the words in the string, using sep as the delimiter string. If maxsplit is given, at most maxsplit splits are done (thus, the list will have at most maxsplit+1 elements). If maxsplit is not specified or -1, then there is no limit on the number of splits (all possible splits are made).

If sep is given, consecutive delimiters are not grouped together and are deemed to delimit empty strings (for example, '1,,2'.split(',') returns ) {} //['1', ”, '2']). The sep argument may consist of multiple characters (for example, '1<>2<>3'.split('<>') returns ) {} //['1', '2', '3']). Splitting an empty string with a specified separator returns ) {} //[”].

For example:

>>> >>> '1,2,3'.split(','){} ) {} //['1', '2', '3'] >>> '1,2,3'.split(',', maxsplit=1){} ) {} //['1', '2,3'] >>> '1,2,,3,'.split(','){} ) {} //['1', '2', ”, '3', ”]

If sep is not specified or is None, a different splitting algorithm is applied: runs of consecutive whitespace are regarded as a single separator, and the result will contain no empty strings at the start or end if the string has leading or trailing whitespace. Consequently, splitting an empty string or a string consisting of just whitespace with a None separator returns ) {} //[].

For example:

>>> >>> '1 2 3'.split(){} ) {} //['1', '2', '3'] >>> '1 2 3'.split(maxsplit=1){} ) {} //['1', '2 3'] >>> ' 1 2 3 '.split(){} ) {} //['1', '2', '3']

func SplitLines

func SplitLines(s string, keepends bool) []string

Return a list of the lines in the string, breaking at line boundaries. Line breaks are not included in the resulting list unless keepends is given and true.

This method splits on the following line boundaries. In particular, the boundaries are a superset of universal newlines.

\n - Line Feed \r - Carriage Return \r\n - Carriage Return + Line Feed \v or \x0b - Line Tabulation \f or \x0c - Form Feed \x1c - File Separator \x1d - Group Separator \x1e - Record Separator \x85 - Next Line (C1 Control Code) \u2028 - Line Separator \u2029 - Paragraph Separator Unlike split() when a delimiter string sep is given, this method returns an empty list for the empty string, and a terminal line break does not result in an extra line:

func StartsWith

func StartsWith(s string, prefix string, start, end *int) bool

Return True if string starts with the prefix, otherwise return False. prefix can also be a tuple of prefixes to look for. With optional start, test string beginning at that position. With optional end, stop comparing string at that position.

func Strip

func Strip(s string, cutset string) string

Return a copy of the string with the leading and trailing characters removed. The chars argument is a string specifying the set of characters to be removed. If omitted or None, the chars argument defaults to removing whitespace. The chars argument is not a prefix or suffix; rather, all combinations of its values are stripped:

>>> >>> ' spacious '.strip(){} 'spacious' >>> 'www.example.com'.strip('cmowz.'){} 'example'

The outermost leading and trailing chars argument values are stripped from the string. Characters are removed from the leading end until reaching a string character that is not contained in the set of characters in chars. A similar action takes place on the trailing end. For example:

>>> >>> comment_string = '#....... Section 3.2.1 Issue #32 .......' >>> comment_string.strip('.#! '){} 'Section 3.2.1 Issue #32'

func SwapCase

func SwapCase(s string) string

Return a copy of the string with uppercase characters converted to lowercase and vice versa. Note that it is not necessarily true that s.swapcase().swapcase() == s.

func Title

func Title(s string) string

Return a titlecased version of the string where words start with an uppercase character and the remaining characters are lowercase.

For example:

>>> >>> 'Hello world'.title() 'Hello World'

The algorithm uses a simple language-independent definition of a word as groups of consecutive letters. The definition works in many contexts but it means that apostrophes in contractions and possessives form word boundaries, which may not be the desired result:

>>> >>> "they're bill's friends from the UK".title(){} "They'Re Bill'S Friends From The Uk"

The string.capwords() function does not have this problem, as it splits words on spaces only.

func Upper

func Upper(s string) string

Return a copy of the string with all the cased characters converted to uppercase. Note that s.upper().isupper() might be False if s contains uncased characters or if the Unicode category of the resulting character(s) is not “Lu” (Letter, uppercase), but e.g. “Lt” (Letter, titlecase).

The uppercasing algorithm used is described in section 3.13 'Default Case Folding' of the Unicode Standard. words on spaces only.

func WithTypeJugglingString

func WithTypeJugglingString(d *Dialect)

func ZFill

func ZFill(s string, width int) string

Return a copy of the string left filled with ASCII '0' digits to make a string of length width. A leading sign prefix ('+'/'-') is handled by inserting the padding after the sign character rather than before. The original string is returned if width is less than or equal to len(s).

For example:

>>> >>> "42".zfill(5){} '00042' >>> "-42".zfill(5){} '-0042'

Types

type AttributeGetter

type AttributeGetter interface {
	Get(string) (any, bool)
}

Used to resolve nested kw-args

type Dialect

type Dialect struct {
	// contains filtered or unexported fields
}

func NewDialect

func NewDialect(version float64, options ...DialectOption) Dialect

func (Dialect) CloneWithOptions

func (d Dialect) CloneWithOptions(options ...DialectOption) Dialect

func (Dialect) Format

func (d Dialect) Format(s string, vargs []any, kwarg map[string]any) (string, error)

func (Dialect) NewFormatterSpecFromStr

func (d Dialect) NewFormatterSpecFromStr(format string) (FormatSpec, error)

type DialectOption

type DialectOption func(*Dialect)

type FormatSpec

type FormatSpec struct {
	Fill                rune // Fill character
	Align               rune // Alignment character ('<' for left, '>' for right, '^' for center, '=' for numeric only)
	Sign                rune // Sign character ('+' for both, '-' for negative only, ' ' for leading space)
	CoercesNegativeZero bool // coerces negative zero floating-point values to positive zero after rounding to the format precision.
	Alternate           bool // Alternate form ('#' for alternative form)
	ZeroPadding         bool // Zero padding ('0' for zero padding)
	MinWidth            uint // Minimum width
	GroupingOption      rune // Grouping option (',' or '_')
	Precision           uint // Precision
	Type                rune // Type character ('b', 'c', 'd', 'o', 'x', 'X', 'e', 'E', 'f', 'F', 'g', 'G', '%')
	// contains filtered or unexported fields
}

FormatSpec represents the format specification for formatting values format_spec ::= [[fill]align][sign]["z"]["#"]["0"][width][grouping_option]["." precision][type]

func NewFormatterSpecFromStr

func NewFormatterSpecFromStr(format string) (FormatSpec, error)

func (FormatSpec) AlignIsValid

func (f FormatSpec) AlignIsValid() bool

func (FormatSpec) ExpectFloatType

func (f FormatSpec) ExpectFloatType() bool

func (FormatSpec) ExpectIntType

func (f FormatSpec) ExpectIntType() bool

func (FormatSpec) ExpectNumericType

func (f FormatSpec) ExpectNumericType() bool

func (FormatSpec) ExpectStringType

func (f FormatSpec) ExpectStringType() bool

func (FormatSpec) Format

func (f FormatSpec) Format(v any) (string, error)

func (FormatSpec) FormatBool

func (f FormatSpec) FormatBool(value bool) (string, error)

func (FormatSpec) FormatFloat

func (f FormatSpec) FormatFloat(value float64) (string, error)

func (FormatSpec) FormatInt

func (f FormatSpec) FormatInt(value int64) (string, error)

FormatInt formats an integer according to the given type.

func (FormatSpec) FormatValue

func (f FormatSpec) FormatValue(v any) (string, ValueCategory, error)

func (FormatSpec) GroupingOptionIsValid

func (f FormatSpec) GroupingOptionIsValid() bool

func (FormatSpec) SignIsValid

func (f FormatSpec) SignIsValid() bool

func (FormatSpec) String

func (f FormatSpec) String() string

func (FormatSpec) TypeIsValid

func (f FormatSpec) TypeIsValid() bool

func (FormatSpec) Validate

func (f FormatSpec) Validate() error

type Formatter

type Formatter interface {
	Format(format string) (string, error)
}

Any value which implements formatter will itself decide how a formatting string should be interpreted. If not the default formatter is used.

type KwArgs

type KwArgs map[string]any

KwArgs adds AttributeGetter interface to map[string]any

func (KwArgs) Get

func (k KwArgs) Get(key string) (any, bool)

type ListArgs

type ListArgs []any

KwArgs adds AttributeGetter interface to map[string]any

func (ListArgs) Get

func (k ListArgs) Get(key string) (any, bool)

type PyString

type PyString string

func New

func New(s string) PyString

func (PyString) CapWords

func (pys PyString) CapWords() PyString

Split the argument into words using str.split(), capitalize each word using str.capitalize(), and join the capitalized words using str.join(). If the optional second argument sep is absent or None, runs of whitespace characters are replaced by a single space and leading and trailing whitespace are removed, otherwise sep is used to split and join the words.

func (PyString) Capitalize

func (pys PyString) Capitalize() PyString

Return a copy of the string with its first character capitalized and the rest lowercased.

func (PyString) Casefold

func (pys PyString) Casefold() PyString

Return a casefolded copy of the string. Casefolded strings may be used for caseless matching.

Casefolding is similar to lowercasing but more aggressive because it is intended to remove all case distinctions in a string. For example, the German lowercase letter 'ß' is equivalent to "ss". Since it is already lowercase, lower() would do nothing to 'ß'; casefold() converts it to "ss".

The casefolding algorithm is described in section 3.13 ‘Default Case Folding’ of the Unicode Standard.

New in version 3.3.

func (PyString) Center

func (pys PyString) Center(width int, fillchar rune) PyString

Return centered in a string of length width. Padding is done using the specified fillchar (default is an ASCII space). The original string is returned if width is less than or equal to len(s).

func (PyString) Count

func (pys PyString) Count(substr PyString, start, end *int) int

Return the number of non-overlapping occurrences of substring sub in the range ) {} //[start, end]. Optional arguments start and end are interpreted as in slice notation.

If sub is empty, returns the number of empty strings between characters which is the length of the string plus one.

func (PyString) Encode

func (pys PyString) Encode(encoding string, errors string) ([]byte, error)

Return the string encoded to bytes. encoding defaults to 'utf-8'; see Standard Encodings for possible values. errors controls how encoding errors are handled. If 'strict' (the default), a UnicodeError exception is raised. Other possible values are 'ignore', 'replace', 'xmlcharrefreplace', 'backslashreplace' and any other name registered via codecs.register_error(). See Error Handlers for details. For performance reasons, the value of errors is not checked for validity unless an encoding error actually occurs, Python Development Mode is enabled or a debug build is used.

func (PyString) EndsWith

func (pys PyString) EndsWith(substr PyString, start, end *int) bool

Return True if the string ends with the specified suffix, otherwise return False. suffix can also be a tuple of suffixes to look for. With optional start, test beginning at that position. With optional end, stop comparing at that position.

func (PyString) ExpandTabs

func (pys PyString) ExpandTabs(substr PyString, tabsize *int) PyString

Return a copy of the string where all tab characters are replaced by one or more spaces, depending on the current column and the given tab size. Tab positions occur every tabsize characters (default is 8, giving tab positions at columns 0, 8, 16 and so on). To expand the string, the current column is set to zero and the string is examined character by character. If the character is a tab (\t), one or more space characters are inserted in the result until the current column is equal to the next tab position. (The tab character itself is not copied.) If the character is a newline (\n) or return (\r), it is copied and the current column is reset to zero. Any other character is copied unchanged and the current column is incremented by one regardless of how the character is represented when printed.

>>> >>> '01\t012\t0123\t01234'.expandtabs(){} '01 012 0123 01234' >>> '01\t012\t0123\t01234'.expandtabs(4){} '01 012 0123 01234'

func (PyString) Find

func (pys PyString) Find(substr PyString, start, end *int) int

Return True if the string ends with the specified suffix, otherwise return False. suffix can also be a tuple of suffixes to look for. With optional start, test beginning at that position. With optional end, stop comparing at that position.

func (PyString) Format

func (s PyString) Format(vargs []any, kwarg map[string]any) (PyString, error)

Perform a string formatting operation. The string on which this method is called can contain literal text or replacement fields delimited by braces {}. Each replacement field contains either the numeric index of a positional argument, or the name of a keyword argument. Returns a copy of the string where each replacement field is replaced with the string value of the corresponding argument.

>>> >>> "The sum of 1 + 2 is {0}".format(1+2){} 'The sum of 1 + 2 is 3'

See Format String Syntax for a description of the various formatting options that can be specified in format strings.

Changes in python versions are captured by different dialects.

func (PyString) FormatMap

func (s PyString) FormatMap(vargs []any, kwarg map[string]any) (PyString, error)

Alias for Format

func (PyString) FormatMapWithDialect

func (s PyString) FormatMapWithDialect(d Dialect, vargs []any, kwarg map[string]any) (PyString, error)

Alias for FormatMapWithDialect

func (PyString) FormatWithDialect

func (s PyString) FormatWithDialect(d Dialect, vargs []any, kwarg map[string]any) (PyString, error)

Perform a string formatting operation. The string on which this method is called can contain literal text or replacement fields delimited by braces {}. Each replacement field contains either the numeric index of a positional argument, or the name of a keyword argument. Returns a copy of the string where each replacement field is replaced with the string value of the corresponding argument.

>>> >>> "The sum of 1 + 2 is {0}".format(1+2){} 'The sum of 1 + 2 is 3'

See Format String Syntax for a description of the various formatting options that can be specified in format strings.

func (PyString) Idx

func (pys PyString) Idx(start, end *int) (PyString, error)

Idx replicates indexing behavior in python. As such it supports negative indexing and don't crash on out of bound indexes.

func (PyString) IsASCII

func (pys PyString) IsASCII() bool

Return True if all characters in the string are decimal characters and there is at least one character, False otherwise. Decimal characters are those that can be used to form numbers in base 10, e.g. U+0660, ARABIC-INDIC DIGIT ZERO. Formally a decimal character is a character in the Unicode General Category “Nd”.

func (PyString) IsAlnum

func (pys PyString) IsAlnum() bool

Return True if all characters in the string are alphanumeric and there is at least one character, False otherwise.

func (PyString) IsAlpha

func (pys PyString) IsAlpha() bool

Return True if all characters in the string are alphabetic and there is at least one character, False otherwise. Alphabetic characters are those characters defined in the Unicode character database as “Letter”, i.e., those with general category property being one of “Lm”, “Lt”, “Lu”, “Ll”, or “Lo”. Note that this is different from the Alphabetic property defined in the section 4.10 ‘Letters, Alphabetic, and Ideographic’ of the Unicode Standard.

func (PyString) IsDecimal

func (pys PyString) IsDecimal() bool

Return True if all characters in the string are decimal characters and there is at least one character, False otherwise. Decimal characters are those that can be used to form numbers in base 10, e.g. U+0660, ARABIC-INDIC DIGIT ZERO. Formally a decimal character is a character in the Unicode General Category “Nd”.

func (PyString) IsDigit

func (pys PyString) IsDigit() bool

Return True if all characters in the string are digits and there is at least one character, False otherwise. Digits include decimal characters and digits that need special handling, such as the compatibility superscript digits. This covers digits which cannot be used to form numbers in base 10, like the Kharosthi numbers. Formally, a digit is a character that has the property value Numeric_Type=Digit or Numeric_Type=Decimal.

func (PyString) IsLower

func (pys PyString) IsLower() bool

Return True if all characters in the string are digits and there is at least one character, False otherwise. Digits include decimal characters and digits that need special handling, such as the compatibility superscript digits. This covers digits which cannot be used to form numbers in base 10, like the Kharosthi numbers. Formally, a digit is a character that has the property value Numeric_Type=Digit or Numeric_Type=Decimal.

func (PyString) IsNumeric

func (pys PyString) IsNumeric() bool

Return True if all characters in the string are digits and there is at least one character, False otherwise. Digits include decimal characters and digits that need special handling, such as the compatibility superscript digits. This covers digits which cannot be used to form numbers in base 10, like the Kharosthi numbers. Formally, a digit is a character that has the property value Numeric_Type=Digit or Numeric_Type=Decimal.

func (PyString) IsPrintable

func (pys PyString) IsPrintable() bool

func (PyString) IsSpace

func (pys PyString) IsSpace() bool

Return True if there are only whitespace characters in the string and there is at least one character, False otherwise.

A character is whitespace if in the Unicode character database (see unicodedata), either its general category is Zs (“Separator, space”), or its bidirectional class is one of WS, B, or S.

func (PyString) IsTitle

func (pys PyString) IsTitle() bool

Return True if the string is a titlecased string and there is at least one character, for example uppercase characters may only follow uncased characters and lowercase characters only cased ones. Return False otherwise.

func (PyString) IsUpper

func (pys PyString) IsUpper() bool

Return True if all cased characters ) {} //[4] in the string are uppercase and there is at least one cased character, False otherwise.

>>> >>> 'BANANA'.isupper(){} True >>> 'banana'.isupper(){} False >>> 'baNana'.isupper(){} False >>> ' '.isupper(){} False

func (PyString) JoinString

func (pys PyString) JoinString(it []PyString) PyString

Return a string which is the concatenation of the strings in iterable. A TypeError will be raised if there are any non-string values in iterable, including bytes objects. The separator between elements is the string

func (PyString) JoinStringer

func (pys PyString) JoinStringer(it []fmt.Stringer) PyString

Return a string which is the concatenation of the strings in iterable. A TypeError will be raised if there are any non-string values in iterable, including bytes objects. The separator between elements is the string

func (PyString) LJust

func (pys PyString) LJust(width int, fillchar rune) PyString

Return the string left justified in a string of length width. Padding is done using the specified fillchar (default is an ASCII space). The original string is returned if width is less than or equal to len(s).

func (PyString) LStrip

func (pys PyString) LStrip(cutset string) PyString

Return a copy of the string with leading characters removed. The chars argument is a string specifying the set of characters to be removed. If omitted or None, the chars argument defaults to removing whitespace. The chars argument is not a prefix; rather, all combinations of its values are stripped:

>>> >>> ' spacious '.lstrip(){} 'spacious ' >>> 'www.example.com'.lstrip('cmowz.'){} 'example.com'

See func removeprefix() for a method that will remove a single prefix string rather than all of a set of characters. For example:

>>> >>> 'Arthur: three!'.lstrip('Arthur: '){} 'ee!' >>> 'Arthur: three!'.removeprefix('Arthur: '){} 'three!'

func (PyString) Lower

func (pys PyString) Lower() PyString

Return a copy of the string with all the cased characters ) {} //[4] converted to lowercase.

The lowercasing algorithm used is described in section 3.13 ‘Default Case Folding’ of the Unicode Standard.

func (PyString) Partition

func (pys PyString) Partition(delim string) (PyString, PyString, PyString)

Split the string at the first occurrence of sep, and return a 3-tuple containing the part before the separator, the separator itself, and the part after the separator. If the separator is not found, return a 3-tuple containing the string itself, followed by two empty strings.

func (PyString) RFind

func (pys PyString) RFind(substr string, start, end *int) int

Return the highest index in the string where substring sub is found, such that sub is contained within s) {} //[start:end]. Optional arguments start and end are interpreted as in slice notation. Return -1 on failure.

func (PyString) RJust

func (pys PyString) RJust(width int, fillchar rune) PyString

Return the string right justified in a string of length width. Padding is done using the specified fillchar (default is an ASCII space). The original string is returned if width is less than or equal to len(s).

func (PyString) RPartition

func (pys PyString) RPartition(delim string) (PyString, PyString, PyString)

Split the string at the last occurrence of sep, and return a 3-tuple containing the part before the separator, the separator itself, and the part after the separator. If the separator is not found, return a 3-tuple containing two empty strings, followed by the string itself.

func (PyString) RSplit

func (pys PyString) RSplit(delim string, maxSplit int) []PyString

Return a list of the words in the string, using sep as the delimiter string. If maxsplit is given, at most maxsplit splits are done, the rightmost ones. If sep is not specified or None, any whitespace string is a separator. Except for splitting from the right, rsplit() behaves like split() which is described in detail below.

func (PyString) RStrip

func (pys PyString) RStrip(cutset string) PyString

Return a copy of the string with trailing characters removed. The chars argument is a string specifying the set of characters to be removed. If omitted or None, the chars argument defaults to removing whitespace. The chars argument is not a suffix; rather, all combinations of its values are stripped:

>>> >>> ' spacious '.rstrip(){} ' spacious' >>> 'mississippi'.rstrip('ipz'){} 'mississ'

See func (pys PyString)removesuffix() for a method that will remove a single suffix string rather than all of a set of characters. For example:

>>> >>> 'Monty Python'.rstrip(' Python'){} 'M' >>> 'Monty Python'.removesuffix(' Python'){} 'Monty'

func (PyString) RemovePrefix

func (pys PyString) RemovePrefix(prefix string) PyString

If the string starts with the prefix string, return string) {} //[len(prefix):]. Otherwise, return a copy of the original string:

>>> >>> 'TestHook'.removeprefix('Test'){} 'Hook' >>> 'BaseTestCase'.removeprefix('Test'){} 'BaseTestCase'

New in version 3.9.

func (PyString) RemoveSuffix

func (pys PyString) RemoveSuffix(prefix string) PyString

If the string ends with the suffix string and that suffix is not empty, return string) {} //[:-len(suffix)]. Otherwise, return a copy of the original string:

>>> >>> 'MiscTests'.removesuffix('Tests'){} 'Misc' >>> 'TmpDirMixin'.removesuffix('Tests'){} 'TmpDirMixin'

New in version 3.9.

func (PyString) Replace

func (pys PyString) Replace(old, new string, count int) PyString

Return a copy of the string with all occurrences of substring old replaced by new. If the optional argument count is given, only the first count occurrences are replaced.

func (PyString) Split

func (pys PyString) Split(delim string, maxSplit int) []PyString

Return a list of the words in the string, using sep as the delimiter string. If maxsplit is given, at most maxsplit splits are done (thus, the list will have at most maxsplit+1 elements). If maxsplit is not specified or -1, then there is no limit on the number of splits (all possible splits are made).

If sep is given, consecutive delimiters are not grouped together and are deemed to delimit empty strings (for example, '1,,2'.split(',') returns ) {} //['1', ”, '2']). The sep argument may consist of multiple characters (for example, '1<>2<>3'.split('<>') returns ) {} //['1', '2', '3']). Splitting an empty string with a specified separator returns ) {} //[”].

For example:

>>> >>> '1,2,3'.split(','){} ) {} //['1', '2', '3'] >>> '1,2,3'.split(',', maxsplit=1){} ) {} //['1', '2,3'] >>> '1,2,,3,'.split(','){} ) {} //['1', '2', ”, '3', ”]

If sep is not specified or is None, a different splitting algorithm is applied: runs of consecutive whitespace are regarded as a single separator, and the result will contain no empty strings at the start or end if the string has leading or trailing whitespace. Consequently, splitting an empty string or a string consisting of just whitespace with a None separator returns ) {} //[].

For example:

>>> >>> '1 2 3'.split(){} ) {} //['1', '2', '3'] >>> '1 2 3'.split(maxsplit=1){} ) {} //['1', '2 3'] >>> ' 1 2 3 '.split(){} ) {} //['1', '2', '3']

func (PyString) SplitLines

func (pys PyString) SplitLines(keepends bool) []PyString

Return a list of the lines in the string, breaking at line boundaries. Line breaks are not included in the resulting list unless keepends is given and true.

This method splits on the following line boundaries. In particular, the boundaries are a superset of universal newlines.

\n - Line Feed \r - Carriage Return \r\n - Carriage Return + Line Feed \v or \x0b - Line Tabulation \f or \x0c - Form Feed \x1c - File Separator \x1d - Group Separator \x1e - Record Separator \x85 - Next Line (C1 Control Code) \u2028 - Line Separator \u2029 - Paragraph Separator Unlike split() when a delimiter string sep is given, this method returns an empty list for the empty string, and a terminal line break does not result in an extra line:

func (PyString) StartsWith

func (pys PyString) StartsWith(prefix string, start, end *int) bool

Return True if string starts with the prefix, otherwise return False. prefix can also be a tuple of prefixes to look for. With optional start, test string beginning at that position. With optional end, stop comparing string at that position.

func (PyString) String

func (s PyString) String() string

func (PyString) Strip

func (pys PyString) Strip(cutset string) PyString

Return a copy of the string with the leading and trailing characters removed. The chars argument is a string specifying the set of characters to be removed. If omitted or None, the chars argument defaults to removing whitespace. The chars argument is not a prefix or suffix; rather, all combinations of its values are stripped:

>>> >>> ' spacious '.strip(){} 'spacious' >>> 'www.example.com'.strip('cmowz.'){} 'example'

The outermost leading and trailing chars argument values are stripped from the string. Characters are removed from the leading end until reaching a string character that is not contained in the set of characters in chars. A similar action takes place on the trailing end. For example:

>>> >>> comment_string = '#....... Section 3.2.1 Issue #32 .......' >>> comment_string.strip('.#! '){} 'Section 3.2.1 Issue #32'

func (PyString) SwapCase

func (pys PyString) SwapCase() PyString

Return a copy of the string with uppercase characters converted to lowercase and vice versa. Note that it is not necessarily true that s.swapcase().swapcase() == s.

func (PyString) Title

func (pys PyString) Title() PyString

Return a titlecased version of the string where words start with an uppercase character and the remaining characters are lowercase.

For example:

>>> >>> 'Hello world'.title() 'Hello World'

The algorithm uses a simple language-independent definition of a word as groups of consecutive letters. The definition works in many contexts but it means that apostrophes in contractions and possessives form word boundaries, which may not be the desired result:

>>> >>> "they're bill's friends from the UK".title(){} "They'Re Bill'S Friends From The Uk"

The string.capwords() function does not have this problem, as it splits words on spaces only.

func (PyString) Upper

func (pys PyString) Upper() PyString

Return a copy of the string with all the cased characters converted to uppercase. Note that s.upper().isupper() might be False if s contains uncased characters or if the Unicode category of the resulting character(s) is not “Lu” (Letter, uppercase), but e.g. “Lt” (Letter, titlecase).

The uppercasing algorithm used is described in section 3.13 'Default Case Folding' of the Unicode Standard. words on spaces only.

func (PyString) ZFill

func (pys PyString) ZFill(width int) PyString

Return a copy of the string left filled with ASCII '0' digits to make a string of length width. A leading sign prefix ('+'/'-') is handled by inserting the padding after the sign character rather than before. The original string is returned if width is less than or equal to len(s).

For example:

>>> >>> "42".zfill(5){} '00042' >>> "-42".zfill(5){} '-0042'

type Token

type Token int

Token represents a token in the input string

const (
	EOF Token = iota
	Characters
	ReplacementBlock
	Unknown
)

func (Token) String

func (t Token) String() string

type ValueCategory

type ValueCategory int
const (
	ValueCategoryUnknown ValueCategory = iota
	ValueCategoryString
	ValueCategoryBool
	ValueCategoryInt
	ValueCategoryFloat
)

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL