Extensions > API reference > string

string

A language built-in type to support strings. Examples of string literals:
a = 'abc\ndef'
b = "ab'cd"
c = """multiline string"""

# Strings support slicing (negative index starts from the end):
x = "hello"[2:4]  # "ll"
y = "hello"[1:-1]  # "ell"
z = "hello"[:4]  # "hell"# Slice steps can be used, too:
s = "hello"[::2] # "hlo"
t = "hello"[3:0:-1] # "lle"
Strings are iterable and support the in operator. Examples:
"bc" in "abcd"   # evaluates to True
x = [s for s in "abc"]  # x == ["a", "b", "c"]
Implicit concatenation of strings is not allowed; use the + operator instead. Comparison operators perform a lexicographical comparison; use == to test for equality.

capitalize

string string.capitalize()

Returns a copy of the string with its first character (if any) capitalized and the rest lowercased. This method does not support non-ascii characters.

count

int string.count(sub, start=0, end=None)

Returns the number of (non-overlapping) occurrences of substring sub in string, optionally restricting to [start:end], start being inclusive and end being exclusive.

Parameters

Parameter Description
sub

string

The substring to count.

start

int

Restrict to search from this position.

end

int

optional position before which to restrict to search.

elems

sequence string.elems()

Returns an iterable value containing successive 1-element substrings of the string. Equivalent to [s[i] for i in range(len(s))], except that the returned value might not be a list.

endswith

bool string.endswith(sub, start=0, end=None)

Returns True if the string ends with sub, otherwise False, optionally restricting to [start:end], start being inclusive and end being exclusive.

Parameters

Parameter Description
sub

string; or tuple of strings

The substring to check.

start

int

Test beginning at this position.

end

int

optional position at which to stop comparing.

find

int string.find(sub, start=0, end=None)

Returns the first index where sub is found, or -1 if no such index exists, optionally restricting to [start:end], start being inclusive and end being exclusive.

Parameters

Parameter Description
sub

string

The substring to find.

start

int

Restrict to search from this position.

end

int

optional position before which to restrict to search.

format

string string.format(*args, **kwargs)

Perform string interpolation. Format strings contain replacement fields surrounded by curly braces {}. Anything that is not contained in braces is considered literal text, which is copied unchanged to the output.If you need to include a brace character in the literal text, it can be escaped by doubling: {{ and }}A replacement field can be either a name, a number, or empty. Values are converted to strings using the str function.
# Access in order:
"{} < {}".format(4, 5) == "4 < 5"
# Access by position:
"{1}, {0}".format(2, 1) == "1, 2"
# Access by name:
"x{key}x".format(key = 2) == "x2x"

Parameters

Parameter Description
args

sequence

List of arguments.

kwargs

dict

Dictionary of arguments.

index

int string.index(sub, start=0, end=None)

Returns the first index where sub is found, or raises an error if no such index exists, optionally restricting to [start:end]start being inclusive and end being exclusive.

Parameters

Parameter Description
sub

string

The substring to find.

start

int

Restrict to search from this position.

end

int

optional position before which to restrict to search.

isalnum

bool string.isalnum()

Returns True if all characters in the string are alphanumeric ([a-zA-Z0-9]) and there is at least one character.

isalpha

bool string.isalpha()

Returns True if all characters in the string are alphabetic ([a-zA-Z]) and there is at least one character.

isdigit

bool string.isdigit()

Returns True if all characters in the string are digits ([0-9]) and there is at least one character.

islower

bool string.islower()

Returns True if all cased characters in the string are lowercase and there is at least one character.

isspace

bool string.isspace()

Returns True if all characters are white space characters and the string contains at least one character.

istitle

bool string.istitle()

Returns True if the string is in title case and it contains at least one character. This means that every uppercase character must follow an uncased one (e.g. whitespace) and every lowercase character must follow a cased one (e.g. uppercase or lowercase).

isupper

bool string.isupper()

Returns True if all cased characters in the string are uppercase and there is at least one character.

join

string string.join(elements)

Returns a string in which the string elements of the argument have been joined by this string as a separator. Example:
"|".join(["a", "b", "c"]) == "a|b|c"

Parameters

Parameter Description
elements

The objects to join.

lower

string string.lower()

Returns the lower case version of this string.

lstrip

string string.lstrip(chars=None)

Returns a copy of the string where leading characters that appear in chars are removed. Note that chars is not a prefix: all combinations of its value are removed:
"abcba".lstrip("ba") == "cba"

Parameters

Parameter Description
chars

string

The characters to remove, or all whitespace if None.

partition

tuple string.partition(sep=unbound)

Splits the input string at the first occurrence of the separator sep and returns the resulting partition as a three-element tuple of the form (substring_before, separator, substring_after).

Parameters

Parameter Description
sep

The string to split on.

replace

string string.replace(old, new, count=unbound)

Returns a copy of the string in which the occurrences of old have been replaced with new, optionally restricting the number of replacements to maxsplit.

Parameters

Parameter Description
old

string

The string to be replaced.

new

string

The string to replace with.

count

int

The maximum number of replacements. If omitted, there is no limit.

If --incompatible_string_replace_count is true, a negative value is ignored (so there's no limit) and a None value is an error. Otherwise, a negative value is treated as 0 and a None value is ignored. (See also issue #11244.)

rfind

int string.rfind(sub, start=0, end=None)

Returns the last index where sub is found, or -1 if no such index exists, optionally restricting to [start:end], start being inclusive and end being exclusive.

Parameters

Parameter Description
sub

string

The substring to find.

start

int

Restrict to search from this position.

end

int

optional position before which to restrict to search.

rindex

int string.rindex(sub, start=0, end=None)

Returns the last index where sub is found, or raises an error if no such index exists, optionally restricting to [start:end], start being inclusive and end being exclusive.

Parameters

Parameter Description
sub

string

The substring to find.

start

int

Restrict to search from this position.

end

int

optional position before which to restrict to search.

rpartition

tuple string.rpartition(sep=unbound)

Splits the input string at the last occurrence of the separator sep and returns the resulting partition as a three-element tuple of the form (substring_before, separator, substring_after).

Parameters

Parameter Description
sep

string

The string to split on.

rsplit

list string.rsplit(sep, maxsplit=None)

Returns a list of all the words in the string, using sep as the separator, optionally limiting the number of splits to maxsplit. Except for splitting from the right, this method behaves like split().

Parameters

Parameter Description
sep

string

The string to split on.

maxsplit

int

The maximum number of splits.

rstrip

string string.rstrip(chars=None)

Returns a copy of the string where trailing characters that appear in chars are removed. Note that chars is not a suffix: all combinations of its value are removed:
"abcbaa".rstrip("ab") == "abc"

Parameters

Parameter Description
chars

string

The characters to remove, or all whitespace if None.

split

list string.split(sep, maxsplit=None)

Returns a list of all the words in the string, using sep as the separator, optionally limiting the number of splits to maxsplit.

Parameters

Parameter Description
sep

string

The string to split on.

maxsplit

int

The maximum number of splits.

splitlines

sequence string.splitlines(keepends=False)

Splits the string at line boundaries ('\n', '\r\n', '\r') and returns the result as a list.

Parameters

Parameter Description
keepends

bool

Whether the line breaks should be included in the resulting list.

startswith

bool string.startswith(sub, start=0, end=None)

Returns True if the string starts with sub, otherwise False, optionally restricting to [start:end], start being inclusive and end being exclusive.

Parameters

Parameter Description
sub

string; or tuple of strings

The substring(s) to check.

start

int

Test beginning at this position.

end

int

Stop comparing at this position.

strip

string string.strip(chars=None)

Returns a copy of the string where leading or trailing characters that appear in chars are removed. Note that chars is neither a prefix nor a suffix: all combinations of its value are removed:
"aabcbcbaa".strip("ab") == "cbc"

Parameters

Parameter Description
chars

string

The characters to remove, or all whitespace if None.

title

string string.title()

Converts the input string into title case, i.e. every word starts with an uppercase letter while the remaining letters are lowercase. In this context, a word means strictly a sequence of letters. This method does not support supplementary Unicode characters.

upper

string string.upper()

Returns the upper case version of this string.