Python: String Methods

, , …,

This page is a list of all Python's string methods. For basic tutorial on string, see:

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

Note: this page is still work in progress

Search Substring

checking
syntaxmeaning
str.startswith(prefix,start,end)Return True if string starts with the prefix, else False. prefix can be a tuple, each element is a string. Optional start, end limits the range of positions to check.
str.endswith(suffix, start, end)similar to “startwith”, but check the end.
str.find(substr,start,end)Return index of the first occurrence of substr. Return -1 if substr is not found.
str.rfind(substr,start,end)similar to “find”, but start at right.
str.index(substr,start,end)similar to “find”, but raise ValueError when the substring is not found.
str.rindex(substr,start,end)similar to “index” but start from right.
str.count(substr,start,end)Return the number of non-overlapping occurrences of substring substr.

in the above, the start and end are optional.

Find/Replace

Find/Replace
syntaxmeaning
str.replace("old", "new" , count)replace occurrences of substring. Only first count number of time is done. count is optional.

Trim String

trim string
syntaxmeaning
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.

String/List Conversion

String/List Conversion
syntaxmeaning
str.join(iterable)Change a {list, tuple} into a string, by concatenating elements, and use str as separator.
str.split("sep",maxsplit)Return a list. Split string using "sep" as the delimiter. If maxsplit is given, at most maxsplit splits are done (result list will have at most maxsplit+1 elements). 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 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() returns ['1', '2', '3'], and ' 1 2 3 '.split(None, 1) returns ['1', '2 3 '].
str.rsplit(sep, maxsplit)same as “split” but begin at right.
str.splitlines(keepends)Return a list of the lines in the string, breaking at line boundaries. This method uses the universal newlines approach to splitting lines. Line breaks are not included in the resulting list unless keepends is given and true. For example, 'ab c\n\nde fg\rkl\r\n'.splitlines() returns ['ab c', '', 'de fg', 'kl'], while the same call with splitlines(True) returns ['ab c\n', '\n', 'de fg\r', 'kl\r\n']. 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.
str.partition(sep)Split the string at the first occurrence of sep, and return a 3-tuple containing the part before the separator, the separator itself, and the part after the separator. If the separator is not found, return a 3-tuple containing the string itself, followed by two empty strings.
str.rpartition(sep)same as “partition” but begin at right.

Check Character Case, Character Class

Check Character Case, Character Class
syntaxmeaning
str.isalnum()Return True if all characters are alphanumeric and there is at least one character, else False.
str.isalpha()
str.isdigit()
str.isupper()
str.islower()
str.isspace()check whitespace characters.
str.istitle()true if every word start with cap letter.
unicode.isnumeric()Return True if there are only numeric characters in S, 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.
unicode.isdecimal()Return True if there are only decimal characters in S, False otherwise. Decimal characters include digit characters, and all characters that can be used to form decimal-radix numbers, e.g. U+0660, ARABIC-INDIC DIGIT ZERO.
xxx
syntaxmeaning
str.translate(table[, deletechars])Return a copy of the string where all characters occurring in the optional argument deletechars are removed, and the remaining characters have been mapped through the given translation table, which must be a string of length 256. You can use the maketrans() helper function in the string module to create a translation table. For string objects, set the table argument to None for translations that only delete characters:

Letter Case Conversion

Letter Case Conversion
str.capitalize()capitalize the first character
str.upper()change to uppercase.
str.lower()change to lowercase.
str.swapcase()switch uppercase/lowercase.
str.title()make each word's first letter uppercase.

Formatting Related Methods

Formatting Related Methods
syntaxmeaning
str.format(…)formatting the string. (replace parts with arguments) 〔➤ Python: Formatting String〕.
str.center(n)add space to begin & 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.
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)
# -*- coding: utf-8 -*-
# python
# example of string ljust
x = """something in water"""
y = x.ljust(30,"-")
print y
# something in water------------

String Character Encoding/Decoding, Unicode

String Character Encoding/Decoding
syntaxmeaning
str.decode(coding)Decode the string using coding.
str.encode(coding)Encoded the string using coding. For a list of possible encodings, see section Standard Encodings.

For list of encoding, see: 7.8. codecs — Codec registry and base classes — Python v2.7.6 documentation #codec-base-classes

blog comments powered by Disqus