Skip to content

Python String API

Python str methods for manipulating text — splitting, replacing, searching, formatting and transforming strings.

1 class · 10 methods

str

10 methods

Built-in string type. Immutable sequence of Unicode code points.

str.split(sep=None, maxsplit=-1)

Return a list of substrings split at sep. If sep is None, splits on any whitespace and discards empty strings.

Parameters

NameTypeDescription
sepstr | NoneDelimiter to split on. None splits on whitespace.
maxsplitintMaximum number of splits (-1 for no limit).

Returns

list[str]

Example

python
'a,b,c'.split(',')        # ['a', 'b', 'c']
'  hello world  '.split()  # ['hello', 'world']
'a-b-c'.split('-', 1)     # ['a', 'b-c']
str.replace(old, new, count=-1)

Return a copy with all occurrences of substring old replaced by new.

Parameters

NameTypeDescription
oldstrSubstring to replace.
newstrReplacement string.
countintMaximum replacements (-1 for all).

Returns

str

Example

python
'hello world'.replace('world', 'Python')  # 'hello Python'
'a-b-c'.replace('-', '_', 1)              # 'a_b-c'
str.find(sub[, start[, end]])

Return the lowest index where sub is found, or -1 if not found. Does not raise.

Parameters

NameTypeDescription
substrSubstring to find.
startintStart index (inclusive).
endintEnd index (exclusive).

Returns

int

Example

python
'hello world'.find('world')  # 6
'hello'.find('z')            # -1
'abcabc'.find('a', 1)        # 3
str.format(*args, **kwargs)

Format the string using replacement fields {0}, {name}, etc. Predecessor of f-strings.

Parameters

NameTypeDescription
*argsAnyPositional arguments for numbered fields.
**kwargsAnyKeyword arguments for named fields.

Returns

str

Example

python
'{} {}'.format('a', 'b')            # 'a b'
'{name}={value}'.format(name='x', value=10)  # 'x=10'
'{0:.2f}'.format(3.14159)                    # '3.14'
str.join(iterable)

Concatenate the strings in iterable, using the string as separator.

Parameters

NameTypeDescription
iterableIterable[str]Iterable of strings to join.

Returns

str

Example

python
','.join(['a', 'b', 'c'])   # 'a,b,c'
'-'.join('abc')            # 'a-b-c'
' '.join(['hello', 'world'])  # 'hello world'
str.strip([chars])

Return a copy with leading and trailing characters removed. Default removes whitespace.

Parameters

NameTypeDescription
charsstr | NoneCharacters to remove (None = whitespace).

Returns

str

Example

python
'  hi  '.strip()      # 'hi'
'xxhelloxx'.strip('x')  # 'hello'
str.startswith(prefix[, start[, end]])

Return True if the string starts with prefix.

Parameters

NameTypeDescription
prefixstr | tuple[str, ...]Prefix or tuple of prefixes to check.
startintStart index.
endintEnd index.

Returns

bool

Example

python
'hello'.startswith('he')        # True
'file.py'.startswith(('a', 'f'))  # True
str.endswith(suffix[, start[, end]])

Return True if the string ends with suffix.

Parameters

NameTypeDescription
suffixstr | tuple[str, ...]Suffix or tuple of suffixes to check.
startintStart index.
endintEnd index.

Returns

bool

Example

python
'hello'.endswith('lo')        # True
'file.py'.endswith(('.py', '.js'))  # True
str.upper()

Return a copy with all cased characters converted to uppercase.

Returns

str

Example

python
'hello'.upper()  # 'HELLO'
str.lower()

Return a copy with all cased characters converted to lowercase.

Returns

str

Example

python
'HELLO'.lower()  # 'hello'