Documentation
¶
Overview ¶
Package pystring provides Python-compatible string methods.
Index ¶
- Variables
- func CapWords(s string) string
- func Capitalize(s string) string
- func Casefold(s string) string
- func Center(s string, width int, fillchar rune) string
- func Count(s, subStr string, start, end *int) int
- func Encode(str, encoding, errors string) ([]byte, error)
- func EndsWith(s, subStr string, start, end *int) bool
- func ExpandTabs(s string, tabSize *int) string
- func Find(s, subStr string, start, end *int) int
- func Format(s string, vargs []any, kwarg map[string]any) (string, error)
- func FormatMap(s string, vargs []any, kwarg map[string]any) (string, error)
- func FormatMapWithDialect(d Dialect, s string, vargs []any, kwarg map[string]any) (string, error)
- func FormatWithDialect(d Dialect, s string, vargs []any, kwarg map[string]any) (string, error)
- func Idx(s string, start, end *int) (string, error)
- func IndexFirstNonDigit(s string) int
- func IsASCII(s string) bool
- func IsAlnum(s string) bool
- func IsAlpha(s string) bool
- func IsDecimal(s string) bool
- func IsDigit(s string) bool
- func IsLower(s string) bool
- func IsNumeric(s string) bool
- func IsPrintable(s string) bool
- func IsSpace(s string) bool
- func IsTitle(s string) bool
- func IsUpper(s string) bool
- func JoinString[T ~string](s T, it []T) string
- func JoinStringer[T fmt.Stringer](s string, it []T) string
- func LJust(s string, width int, fillchar rune) string
- func LStrip(s string, cutset string) string
- func Lower(s string) string
- func NewScanner(s string, d Dialect) *pyStringScanner
- func Partition(s string, delim string) (string, string, string)
- func RFind(s string, substr string, start, end *int) int
- func RJust(s string, width int, fillchar rune) string
- func RPartition(s string, delim string) (string, string, string)
- func RSplit(s string, delim string, maxSplit int) []string
- func RStrip(s string, cutset string) string
- func RemovePrefix(s string, prefix string) string
- func RemoveSuffix(s string, prefix string) string
- func Replace(s string, old, new string, count int) string
- func Split(s string, delim string, maxSplit int) []string
- func SplitLines(s string, keepends bool) []string
- func StartsWith(s string, prefix string, start, end *int) bool
- func Strip(s string, cutset string) string
- func SwapCase(s string) string
- func Title(s string) string
- func Upper(s string) string
- func WithTypeJugglingString(d *Dialect)
- func ZFill(s string, width int) string
- type AttributeGetter
- type Dialect
- type DialectOption
- type FormatSpec
- func (f FormatSpec) AlignIsValid() bool
- func (f FormatSpec) ExpectFloatType() bool
- func (f FormatSpec) ExpectIntType() bool
- func (f FormatSpec) ExpectNumericType() bool
- func (f FormatSpec) ExpectStringType() bool
- func (f FormatSpec) Format(v any) (string, error)
- func (f FormatSpec) FormatBool(value bool) (string, error)
- func (f FormatSpec) FormatFloat(value float64) (string, error)
- func (f FormatSpec) FormatInt(value int64) (string, error)
- func (f FormatSpec) FormatValue(v any) (string, ValueCategory, error)
- func (f FormatSpec) GroupingOptionIsValid() bool
- func (f FormatSpec) SignIsValid() bool
- func (f FormatSpec) String() string
- func (f FormatSpec) TypeIsValid() bool
- func (f FormatSpec) Validate() error
- type Formatter
- type KwArgs
- type ListArgs
- type PyString
- func (pys PyString) CapWords() PyString
- func (pys PyString) Capitalize() PyString
- func (pys PyString) Casefold() PyString
- func (pys PyString) Center(width int, fillchar rune) PyString
- func (pys PyString) Count(substr PyString, start, end *int) int
- func (pys PyString) Encode(encoding string, errors string) ([]byte, error)
- func (pys PyString) EndsWith(substr PyString, start, end *int) bool
- func (pys PyString) ExpandTabs(substr PyString, tabsize *int) PyString
- func (pys PyString) Find(substr PyString, start, end *int) int
- func (pys PyString) Format(vargs []any, kwarg map[string]any) (PyString, error)
- func (pys PyString) FormatMap(vargs []any, kwarg map[string]any) (PyString, error)
- func (pys PyString) FormatMapWithDialect(d Dialect, vargs []any, kwarg map[string]any) (PyString, error)
- func (pys PyString) FormatWithDialect(d Dialect, vargs []any, kwarg map[string]any) (PyString, error)
- func (pys PyString) Idx(start, end *int) (PyString, error)
- func (pys PyString) IsASCII() bool
- func (pys PyString) IsAlnum() bool
- func (pys PyString) IsAlpha() bool
- func (pys PyString) IsDecimal() bool
- func (pys PyString) IsDigit() bool
- func (pys PyString) IsLower() bool
- func (pys PyString) IsNumeric() bool
- func (pys PyString) IsPrintable() bool
- func (pys PyString) IsSpace() bool
- func (pys PyString) IsTitle() bool
- func (pys PyString) IsUpper() bool
- func (pys PyString) JoinString(it []PyString) PyString
- func (pys PyString) JoinStringer(it []fmt.Stringer) PyString
- func (pys PyString) LJust(width int, fillchar rune) PyString
- func (pys PyString) LStrip(cutset string) PyString
- func (pys PyString) Lower() PyString
- func (pys PyString) Partition(delim string) (PyString, PyString, PyString)
- func (pys PyString) RFind(substr string, start, end *int) int
- func (pys PyString) RJust(width int, fillchar rune) PyString
- func (pys PyString) RPartition(delim string) (PyString, PyString, PyString)
- func (pys PyString) RSplit(delim string, maxSplit int) []PyString
- func (pys PyString) RStrip(cutset string) PyString
- func (pys PyString) RemovePrefix(prefix string) PyString
- func (pys PyString) RemoveSuffix(prefix string) PyString
- func (pys PyString) Replace(old, new string, count int) PyString
- func (pys PyString) Split(delim string, maxSplit int) []PyString
- func (pys PyString) SplitLines(keepends bool) []PyString
- func (pys PyString) StartsWith(prefix string, start, end *int) bool
- func (pys PyString) String() string
- func (pys PyString) Strip(cutset string) PyString
- func (pys PyString) SwapCase() PyString
- func (pys PyString) Title() PyString
- func (pys PyString) Upper() PyString
- func (pys PyString) ZFill(width int) PyString
- type Token
- type ValueCategory
Constants ¶
This section is empty.
Variables ¶
var DefaultDialect = NewDialect(3.11)
DefaultDialect captures the format specifier behavior for Python 3.11. There have been multiple changes in Python regarding how format specifiers are handled; to enable all possible formats we capture these changes as feature flags which can be opted in or out of.
var DialectPython3_0 = NewDialect(3.0)
var DialectPython3_10 = NewDialect(3.10)
var DialectPython3_11 = NewDialect(3.11)
Functions ¶
func CapWords ¶
CapWords splits the argument into words using str.split(), capitalizes each word using str.capitalize(), and joins 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 ¶
Capitalize returns a copy of the string with its first character capitalized and the rest lowercased.
func Casefold ¶
Casefold returns 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 ¶
Center returns the string 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 ¶
Count returns 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 ¶
Encode returns 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 ¶
EndsWith returns True if the string ends with the specified suffix, otherwise returns 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 ¶
ExpandTabs returns 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 ¶
Find returns the lowest index in the string where substring sub is found within the slice [start:end]. Optional arguments start and end are interpreted as in slice notation. Returns -1 if sub is not found.
func Format ¶
Format performs 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 FormatMapWithDialect ¶
FormatMapWithDialect is an alias for FormatWithDialect.
func FormatWithDialect ¶
FormatWithDialect performs 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 ¶
Idx replicates indexing behavior in python. As such it supports negative indexing and don't crash on out of bound indexes.
func IndexFirstNonDigit ¶
func IsAlnum ¶
IsAlnum returns True if all characters in the string are alphanumeric and there is at least one character, False otherwise.
func IsAlpha ¶
IsAlpha returns 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 ¶
IsDecimal returns 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 ¶
IsDigit returns 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 ¶
IsLower returns True if all cased characters in the string are lowercase and there is at least one cased character, False otherwise.
func IsNumeric ¶
IsNumeric returns True if all characters in the string are numeric and there is at least one character, False otherwise. Numeric characters include digit characters and all characters that have the Unicode numeric value property, e.g. U+2155, VULGAR FRACTION ONE FIFTH. Formally, numeric characters are those with the property value Numeric_Type=Digit, Numeric_Type=Decimal, or Numeric_Type=Numeric.
func IsPrintable ¶
IsPrintable returns 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 ¶
IsSpace returns 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 ¶
IsTitle returns 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. Returns False otherwise.
func IsUpper ¶
IsUpper returns 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 ¶
JoinString returns 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 LJust ¶
LJust returns 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 ¶
LStrip returns 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 ¶
Lower returns a copy of the string with all the cased characters converted to lowercase.
The lowercasing algorithm used is described in section 3.13 ‘Default Case Folding’ of the Unicode Standard.
func NewScanner ¶
func Partition ¶
Partition splits the string at the first occurrence of sep, and returns a 3-tuple containing the part before the separator, the separator itself, and the part after the separator. If the separator is not found, returns a 3-tuple containing the string itself, followed by two empty strings.
func RFind ¶
RFind returns 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. Returns -1 on failure.
func RJust ¶
RJust returns 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 ¶
RPartition splits the string at the last occurrence of sep, and returns a 3-tuple containing the part before the separator, the separator itself, and the part after the separator. If the separator is not found, returns a 3-tuple containing two empty strings, followed by the string itself.
func RSplit ¶
RSplit returns 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 ¶
RStrip returns 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 ¶
RemovePrefix returns the string with the prefix removed. 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 ¶
RemoveSuffix returns the string with the suffix removed. 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 ¶
Replace returns 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 ¶
Split returns 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 ¶
SplitLines returns 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 ¶
StartsWith returns True if string starts with the prefix, otherwise returns 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 ¶
Strip returns 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 ¶
SwapCase returns 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 ¶
Title returns 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 ¶
Upper returns 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 ¶
ZFill returns 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 ¶
AttributeGetter is 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) 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) 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 ¶
Formatter is implemented by any value that decides how a formatting string should be interpreted. If not implemented, the default formatter is used.
type PyString ¶
type PyString string
func (PyString) CapWords ¶
CapWords splits the argument into words using str.split(), capitalizes each word using str.capitalize(), and joins 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 ¶
Capitalize returns a copy of the string with its first character capitalized and the rest lowercased.
func (PyString) Casefold ¶
Casefold returns 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 ¶
Center returns the string 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 ¶
Count returns 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 ¶
Encode returns 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 ¶
EndsWith returns True if the string ends with the specified suffix, otherwise returns 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 ¶
ExpandTabs returns 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 ¶
Find returns the lowest index in the string where substring sub is found within the slice [start:end]. Optional arguments start and end are interpreted as in slice notation. Returns -1 if sub is not found.
func (PyString) Format ¶
Format performs 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) FormatMapWithDialect ¶
func (pys PyString) FormatMapWithDialect(d Dialect, vargs []any, kwarg map[string]any) (PyString, error)
FormatMapWithDialect is an alias for FormatWithDialect.
func (PyString) FormatWithDialect ¶
func (pys PyString) FormatWithDialect(d Dialect, vargs []any, kwarg map[string]any) (PyString, error)
FormatWithDialect performs 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 ¶
Idx replicates indexing behavior in python. As such it supports negative indexing and don't crash on out of bound indexes.
func (PyString) IsASCII ¶
IsASCII returns True if all characters in the string are ASCII, False otherwise.
func (PyString) IsAlnum ¶
IsAlnum returns True if all characters in the string are alphanumeric and there is at least one character, False otherwise.
func (PyString) IsAlpha ¶
IsAlpha returns 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 ¶
IsDecimal returns 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 ¶
IsDigit returns 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 ¶
IsLower returns True if all cased characters in the string are lowercase and there is at least one cased character, False otherwise.
func (PyString) IsNumeric ¶
IsNumeric returns True if all characters in the string are numeric and there is at least one character, False otherwise. Numeric characters include digit characters and all characters that have the Unicode numeric value property, e.g. U+2155, VULGAR FRACTION ONE FIFTH. Formally, numeric characters are those with the property value Numeric_Type=Digit, Numeric_Type=Decimal, or Numeric_Type=Numeric.
func (PyString) IsPrintable ¶
func (PyString) IsSpace ¶
IsSpace returns 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 ¶
IsTitle returns 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. Returns False otherwise.
func (PyString) IsUpper ¶
IsUpper returns 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 ¶
JoinString returns 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 ¶
JoinStringer returns 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 ¶
LJust returns 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 ¶
LStrip returns 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 ¶
Lower returns a copy of the string with all the cased characters converted to lowercase.
The lowercasing algorithm used is described in section 3.13 ‘Default Case Folding’ of the Unicode Standard.
func (PyString) Partition ¶
Partition splits the string at the first occurrence of sep, and returns a 3-tuple containing the part before the separator, the separator itself, and the part after the separator. If the separator is not found, returns a 3-tuple containing the string itself, followed by two empty strings.
func (PyString) RFind ¶
RFind returns 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. Returns -1 on failure.
func (PyString) RJust ¶
RJust returns 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 ¶
RPartition splits the string at the last occurrence of sep, and returns a 3-tuple containing the part before the separator, the separator itself, and the part after the separator. If the separator is not found, returns a 3-tuple containing two empty strings, followed by the string itself.
func (PyString) RSplit ¶
RSplit returns 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 ¶
RStrip returns 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 ¶
RemovePrefix returns the string with the prefix removed. 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 ¶
RemoveSuffix returns the string with the suffix removed. 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 ¶
Replace returns 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 ¶
Split returns 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 ¶
SplitLines returns 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 ¶
StartsWith returns True if string starts with the prefix, otherwise returns 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) Strip ¶
Strip returns 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 ¶
SwapCase returns 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 ¶
Title returns 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 ¶
Upper returns 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 ¶
ZFill returns 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 ValueCategory ¶
type ValueCategory int
const ( ValueCategoryUnknown ValueCategory = iota ValueCategoryString ValueCategoryBool ValueCategoryInt ValueCategoryFloat )
Source Files
¶
- dialect.go
- dialect_format.go
- dialect_formatter_spec.go
- kwargs.go
- pystring.go
- str_captitalize.go
- str_capwords.go
- str_casefold.go
- str_center.go
- str_count.go
- str_encoding.go
- str_endswith.go
- str_expandtabs.go
- str_find.go
- str_format.go
- str_formatmap.go
- str_idx.go
- str_isalnum.go
- str_isalpha.go
- str_isascii.go
- str_isdecimal.go
- str_isdigit.go
- str_islower.go
- str_isnumeric.go
- str_isprintable.go
- str_isspace.go
- str_istitle.go
- str_isupper.go
- str_join.go
- str_ljust.go
- str_lower.go
- str_lstrip.go
- str_partition.go
- str_removeprefix.go
- str_removesuffix.go
- str_replace.go
- str_rfind.go
- str_rjust.go
- str_rpartition.go
- str_rsplit.go
- str_rstrip.go
- str_split.go
- str_splitlines.go
- str_startswith.go
- str_strip.go
- str_swapcase.go
- str_title.go
- str_upper.go
- str_zfill.go
- string_scanner.go