Python: String Methods

By Xah Lee. Date: . Last updated: .

Python strings are not mutable. All string methods return a new string.

Substring

str[n:m]
Return a substring from index n to m.

Negative index counts from end, starting with -1

print("01234"[2:4] == "23")
print("abcd"[0:-2] == "ab")
print("abcd"[2:] == "cd")
str[:m]
From beginning to m.
str[n:]
From n to the end, including the end char.

Length

len(str)
Return the count of chars in str.

Join String

Repeat

str * n
Repeat the string n times.

Search Substring

Find Replace

str.replace(old, new , ?count)
Return a new string, with occurrences of old replace by new. Only first ?count number of time is done.

Trim String

str.strip(?chars)
Remove any char in ?chars at the leading/trailing ends of the string.

The ?chars is a string specifying the set of characters to be removed, defaults to whitespace.

str.rstrip(?chars)
Same as strip, but only do trailing end.
str.lstrip(?chars)
Same as strip, but only do beginning end.

Convert List to String

str.join(iterable)
Change a List or Tuple into a string, by concatenating elements, and use str as separator.

Convert String to List

Check Character Case, Character Class

Letter Case Conversion

Formatting Related Methods

str.format(args)
Formatting the string. (replace parts with arguments) 〔see Python: Format String〕.
str.center(n)
Add space to begin and end of string, so it's centered with respect to n chars.
str.center(n,char)
Fill it with character char
str.ljust(width, ?fillchar)
Add fillchar to the end of string, so total length is width.

fillchar defaults to space. The original string is returned if width is less than or equal to given string length.

print("abc".rjust(5) == "  abc")
print("abc".rjust(5, "-") == "--abc")
str.rjust(width, fillchar)
Same as ljust but done pads on the left.
str.zfill(width)
Return the numeric string left filled with zeros in a string of length width. A sign prefix is handled correctly. The original string is returned if width is less than or equal length.
str.expandtabs()
Replace tab char by space.
str.expandtabs(tabsize)

String Encode, Decode

str.decode(coding)
Decode the string using coding.
str.encode(coding)
Encoded the string using coding.

For a list of possible encodings, see python doc “Standard Encodings”.

Python, String