Python 3 String Methods

List of string methods available in Python 3.

Method Description Examples
capitalize()

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

Result
Bee sting
casefold() Returns a casefolded copy of the string. Casefolded strings may be used for caseless matching.
Result
bee
center(width[, fillchar]) Returns the string centered in a string of length width. Padding can be done using the specified fillchar (the default padding uses an ASCII space). The original string is returned if width is less than or equal to len(s)
Result
----bee-----
count(sub[, start[, end]])

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.

Non-overlapping occurrences means that Python won't double up on characters that have already been counted. For example, using a substring of xxx against xxxx returns 1.

Result
0
5
2
1
0
2
3
encode(encoding="utf-8", errors="strict")

Returns an encoded version of the string as a bytes object. The default encoding is utf-8. errors may be given to set a different error handling scheme. The possible value for errors are:

  • strict (encoding errors raise a UnicodeError)
  • ignore
  • replace
  • xmlcharrefreplace
  • backslashreplace
  • any other name registered via codecs.register_error()
Result
Banana
b'QmFuYW5h'
endswith(suffix[, start[, end]])

Returns True if the string ends with the specified suffix, otherwise it returns False. suffix can also be a tuple of suffixes. When the (optional) start argument is provided, the test begins at that position. With optional end, the test stops comparing at that position.

Result
True
True
False
True
expandtabs(tabsize=8)

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 (the default is 8, giving tab positions at columns 0, 8, 16 and so on).

Result
1 2   3
1       2       3
1           2           3
1    2    3
find(sub[, start[, end]])

Returns the lowest index in the string where substring sub is found within the slice s[start:end]. Optional arguments start and end are interpreted as in slice notation. Returns -1 if sub is not found.

Result
0
-1
3
3
4
-1
-1
format(*args, **kwargs)

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.

Result
Tea and Coffee
Coffee and Tea
Peas and Beans
1, 2, 3
Lunch: Pizza, Wine
format_map(mapping)

Similar to format(**mapping), except that mapping is used directly and not copied to a dictionary. This is useful if for example mapping is a dict subclass.

Result
Lunch: Pizza, Wine
Lunch: Pizza, Drink
Lunch: Food, Wine
index(sub[, start[, end]])

Like find() (above), but raises a ValueError when the substring is not found (find() returns -1 when the substring isn't found).

Result
0
3
3
4
ValueError: substring not found
isalnum()

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

A character c is deemed to be alphanumeric if one of the following returns True:

  • c.isalpha()
  • c.isdecimal()
  • c.isdigit()
  • c.isnumeric()
Result
True
True
False
False
False
isalpha()

Returns True if all characters in the string are alphabetic and there is at least one character. Returns False otherwise.

Result
True
False
False
isdecimal()

Returns True if all characters in the string are decimal characters and there is at least one character. Returns False otherwise.

Result
True
False
False
False
False
False
isdigit()

Returns True if all characters in the string are digits and there is at least one character. Returns False otherwise.

The isdigit() method is often used when working with various unicode characters, such as for superscripts (eg, 2).

Result
True
True
False
False
False
False
isidentifier()

Returns true if the string is a valid identifier according to the language definition, section Identifiers and keywords from the Python docs.

Result
False
True
False
True
True
islower()

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

Result
False
False
True
False
False
True
True
isnumeric()

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

Result
True
True
False
False
False
False
isprintable()

Returns True if all characters in the string are printable or the string is empty. Returns False otherwise.

Nonprintable characters are those characters defined in the Unicode character database as "Other" or "Separator", except for the ASCII space (0x20) which is considered printable.

Result
True
True
True
True
False
False
False
isspace()

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

Whitespace characters are those characters defined in the Unicode character database as "Other" or "Separator" and those with bidirectional property being one of "WS", "B", or "S".

Result
False
True
False
True
True
False
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.

Whitespace characters are those characters defined in the Unicode character database as "Other" or "Separator" and those with bidirectional property being one of "WS", "B", or "S".

Result
False
False
False
True
True
False
True
True
isupper()

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

Result
False
False
True
False
True
False
False
join(iterable)

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.

Result
1-2-3
U.S.A
Dr. Who
ljust(width[, fillchar]) Returns the string left justified in a string of length width. Padding can be done using the specified fillchar (the default padding uses an ASCII space). The original string is returned if width is less than or equal to len(s)
Result
bee---------
lower()

Returns a copy of the string with all the cased characters converted to lowercase.

Result
bee
lstrip([chars])

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 set to None, the chars argument defaults to removing whitespace.

Result
Bee       !
Bee-----
maketrans(x[, y[, z]])

This is a static method that returns a translation table usable for str.translate().

  • If there is only one argument, it must be a dictionary mapping Unicode ordinals (integers) or characters (strings of length 1) to Unicode ordinals, strings (of arbitrary lengths) or set to None. Character keys will then be converted to ordinals.
  • If there are two arguments, they must be strings of equal length, and in the resulting dictionary, each character in x will be mapped to the character at the same position in y.
  • If there is a third argument, it must be a string, whose characters will be mapped to None in the result.
Result
123425 6782
partition(sep)

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, it returns a 3-tuple containing the string itself, followed by two empty strings.

Result
('Python', '-', 'program')
('Python-program', '', '')
replace(old, new[, count])

Returns a copy of the string with all occurrences of substring old replaced by new. If the optional argument count is provided, only the first count occurrences are replaced. For example, if count is 3, only the first 3 occurrences are replaced.

Result
Coffee bag. Coffee cup. Coffee leaves.
Coffee bag. Coffee cup. Tea leaves.
rfind(sub[, start[, end]])

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. This method returns -1 on failure.

Result
0
8
10
9
-1
-1
-1
rindex(sub[, start[, end]])

Like rfind() but raises ValueError when the substring sub is not found.

Result
0
8
10
9
ValueError: substring not found
ValueError: substring not found
ValueError: substring not found
rjust(width[, fillchar]) Returns the string right justified in a string of length width. Padding can be done using the specified fillchar (the default padding uses an ASCII space). The original string is returned if width is less than or equal to len(s)
Result
---------bee
rpartition(sep)

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, it returns a 3-tuple containing the string itself, followed by two empty strings.

Result
('Homer-Jay', '-', 'Simpson')
('', '', 'Homer-Jay-Simpson')
rsplit(sep=None, maxsplit=-1)

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 is set to None, any whitespace string is a separator.

Except for splitting from the right, rsplit() behaves like split() which is described below.

Result
['Homer', 'Jay', 'Simpson']
['Homer-Jay', 'Simpson']
rstrip([chars])

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 set to None, the chars argument defaults to removing whitespace.

Result
Bee !
-----Bee
split(sep=None, maxsplit=-1)

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. If maxsplit is not specified or -1, then there is no limit on the number of splits.

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 [''].

If sep is not specified or is set to 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 [].

Result
['Homer', 'Jay', 'Simpson']
['Homer', 'Jay-Simpson']
['Homer', '', 'Bart', '']
['Homer', ',Bart']
['Homer', 'Bart', 'Marge']
splitlines([keepends])

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 its value is True.

This method splits on the following line boundaries.

Representation Description
\n Line Feed
\r Carriage Return
\n\r 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
Result
['Tea', '', 'and coffee', 'cups']
['Tea\n', '\n', 'and coffee\r', 'cups\r\n']
startswith(prefix[, start[, end]])

Returns True if the string starts with the specified prefix, otherwise it returns False. prefix can also be a tuple of prefixes. When the (optional) start argument is provided, the test begins at that position. With optional end, the test stops comparing at that position.

Result
True
False
True
False
True
strip([chars])

Returns a copy of the string with leading and trailing characters removed. The chars argument is a string specifying the set of characters to be removed. If omitted or set to None, the chars argument defaults to removing whitespace.

Result
Bee !
Bee
swapcase()

Returns a copy of the string with uppercase characters converted to lowercase and vice versa.

Result
hOMER sIMPSON
title()

Returns a title-cased version of the string. Title case is where words start with an uppercase character and the remaining characters are lowercase.

Result
Tea And Coffee
Tea And Coffee
translate(table)

Returns a copy of the string in which each character has been mapped through the given translation table. The table must be an object that implements indexing via __getitem__(), typically a mapping or sequence.

Result
123425 6782
upper()

Returns a copy of the string with all the cased characters converted to uppercase.

Result
BEE
zfill(width)

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).

Result
00036
-0036
+0036