Previous Page
Next Page

9.1. Methods of String Objects

Plain and Unicode strings are immutable sequences, as covered in "Strings" on page 55. All immutable-sequence operations (repetition, concatenation, indexing, slicing) apply to strings. A string object s also supplies several nonmutating methods, as documented in this section. Unless otherwise noted, each method returns a plain string when s is a plain string, or a Unicode string when s is a Unicode string. Terms such as "letters," "whitespace," and so on, refer to the corresponding attributes of the string module, covered in "The string Module" on page 191. See also "Locale Sensitivity" on page 192.

capitalize

s.capitalize( )

Returns a copy of s where the first character, if a letter, is uppercase, and all other letters, if any, are lowercase.

center

s.center(n,fillchar=' ')

Returns a string of length max(len(s),n), with a copy of s in the central part, surrounded by equal numbers of copies of character fillchar on both sides (e.g., 'ciao'.center(2) is 'ciao' and 'x'.center(4,'_') is '_x_ _').

count

s.count(sub,start=0,end=sys.maxint)

Returns the number of nonoverlapping occurrences of substring sub in s[start:end].

encode

s.encode(codec=None,errors='strict')

Returns a plain string obtained from s with the given codec and error handling. See "Unicode" on page 198 for more details.

endswith

s.endswith(suffix,start=0,end=sys.maxint)

Returns true when s[start:end] ends with suffix; otherwise, False.

expandtabs

s.expandtabs(tabsize=8)

Returns a copy of s where each tab character is changed into one or more spaces, with tab stops every tabsize characters.

find

s.find(sub,start=0,end=sys.maxint)

Returns the lowest index in s where substring sub is found, such that sub is entirely contained in s[start:end]. For example, 'banana'.find('na') is 2, as is 'banana'.find('na',1), while 'banana'.find('na',3) is 4, as is 'banana'.find('na',-2). find returns -1 if sub is not found.

index

s.index(sub,start=0,end=sys.maxint)

Like find, but raises ValueError when sub is not found.

isalnum

s.isalnum( )

Returns true when len(s) is greater than 0 and all characters in s are letters or decimal digits. When s is empty, or when at least one character of s is neither a letter nor a decimal digit, isalnum returns False.

isalpha

s.isalpha( )

Returns true when len(s) is greater than 0 and all characters in s are letters. When s is empty, or when at least one character of s is not a letter, isalpha returns False.

isdigit

s.isdigit( )

Returns TRue when len(s) is greater than 0 and all characters in s are digits. When s is empty, or when at least one character of s is not a digit, isdigit returns False.

islower

s.islower( )

Returns TRue when all letters in s are lowercase. When s contains no letters, or when at least one letter of s is uppercase, islower returns False.

isspace

s.isspace( )

Returns true when len(s) is greater than 0 and all characters in s are whitespace. When s is empty, or when at least one character of s is not whitespace, isspace returns False.

istitle

s.istitle( )

Returns true when letters in s are titlecase: a capital letter at the start of each contiguous sequence of letters, all other letters lowercase (e.g., 'King Lear'.istitle( ) is true). When s contains no letters, or when at least one letter of s violates the titlecase condition, istitle returns False (e.g., '1900'.istitle( ) and 'troilus and Cressida'.istitle( ) are False).

isupper

s.isupper( )

Returns true when all letters in s are uppercase. When s contains no letters, or when at least one letter of s is lowercase, isupper returns False.

join

s.join(seq)

Returns the string obtained by concatenating the items of seq, which must be a sequence or other iterable whose items are strings, and interposing a copy of s between each pair of items (e.g., ''.join(str(x) for x in range(7)) is '0123456' and 'x'.join('aeiou') is 'axexixoxu').

ljust

s.ljust(n,fillchar=' ')

Returns a string of length max(len(s),n), with a copy of s at the start, followed by zero or more trailing copies of character fillchar.

lower

s.lower( )

Returns a copy of s with all letters, if any, converted to lowercase.

lstrip

s.lstrip(x=string.whitespace)

Returns a copy of s, removing leading characters that are found in string x.

replace

s.replace(old,new,maxsplit=sys.maxint)

Returns a copy of s with the first maxsplit (or fewer, if there are fewer) nonoverlapping occurrences of substring old replaced by string new (e.g., 'banana'.replace('a','e',2) is 'benena').

rfind

s.rfind(sub,start=0,end=sys.maxint)

Returns the highest index in s where substring sub is found, such that sub is entirely contained in s[start:end]. rfind returns -1 if sub is not found.

rindex

s.rindex(sub,start=0,end=sys.maxint)

Like rfind, but raises ValueError if sub is not found.

rjust

s.rjust(n,fillchar=' ')

Returns a string of length max(len(s),n), with a copy of s at the end, preceded by zero or more leading copies of character fillchar.

rstrip

s.rstrip(x=string.whitespace)

Returns a copy of s, removing leading characters that are found in string x.

split

s.split(sep=None,maxsplit=sys.maxint)

Returns a list L of up to maxsplit+1 strings. Each item of L is a "word" from s, where string sep separates words. When s has more than maxsplit words, the last item of L is the substring of s that follows the first maxsplit words. When sep is None, any string of whitespace separates words (e.g., 'four score and seven years ago'.split(None,3) is ['four','score','and','seven years ago']).

Note the difference between splitting on None (any string of whitespace is a separator) and splitting on ' ' (each single space character, not other whitespace such as tabs and newlines, and not strings, is a separator). For example:

>>> x = 'a  b'  # two spaces between a and b
>>> x.split( )
['a', 'b']
>>> x.split(' ')
['a', '', 'b']

In the first case, the two-spaces string in the middle is a single separator; in the second case, each single space is a separator so that there is an empty string between the spaces.

splitlines

s.splitlines(keepends=False)

Like s.split('\n'). When keepends is true, however, the trailing '\n' is included in each item of the resulting list.

startswith

s.startswith(prefix,start=0,end=sys.maxint)

Returns true when s[start:end] starts with prefix; otherwise, False.

strip

s.strip(x=string.whitespace)

Returns a copy of s, removing both leading and trailing characters that are found in string x.

swapcase

s.swapcase( )

Returns a copy of s with all uppercase letters converted to lowercase and vice versa.

title

s.title( )

Returns a copy of s TRansformed to titlecase: a capital letter at the start of each contiguous sequence of letters, with all other letters, if any, lowercase.

translate

s.translate(table, deletechars='') when s is a plain string s.translate(table) when s is a unicode string

When s is a plain string, returns a copy of s where all characters occurring in string deletechars are removed, and the remaining characters are mapped through translation-table table. table must be a plain string of length 256, and is most often built using function string.maketrans, covered in maketrans on page 192.

When s is a Unicode string, returns a copy of s where characters found in table are translated or deleted. table is a dict whose keys are Unicode ordinals; values are Unicode ordinals, Unicode strings, or None (to delete)for example:

u'banna'.translate({ord('a'):None,ord('n'):u'ze'}) is u'bzeze'

upper

s.upper( )

Returns a copy of s with all letters, if any, converted to uppercase.



Previous Page
Next Page