Previous Section Next Section

9.1 Methods of String Objects

Plain and Unicode strings are immutable sequences, as covered in Chapter 4. All immutable-sequence operations (repetition, concatenation, indexing, slicing) apply to strings. A string object s also supplies several non-mutating 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 later in this chapter. See also the later section Section 9.2.1.

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)

Returns a string of length max(len(s),n), with a copy of s in the central part, surrounded by equal numbers of spaces on both sides (e.g., 'ciao'.center(2) is 'ciao', 'ciao'.center(7) is ' ciao ').

count

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

Returns the number of 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 Section 9.6 later in this chapter 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 decimal 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 has 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 has no letters, or when at least one letter of s violates the titlecase constraint, 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 has 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 of strings, and interposing a copy of s between each pair of items (e.g., ''.join([str(x) for x in range(7)]) is '0123456').

ljust

s.ljust(n)

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

lower

s.lower(  )

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

lstrip

s.lstrip(x=None)

Returns a copy of s with leading whitespace, if any, removed. Since Python 2.2.2, you can optionally pass a string x as an argument, in which case lstrip removes characters found in x rather than removing whitespace.

replace

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

Returns a copy of s with the first maxsplit (or fewer, if there are fewer) non-overlapping 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)

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

rstrip

s.rstrip(x=None)

Returns a copy of s with trailing whitespace, if any, removed. Since Python 2.2.2, you can optionally pass a string x as an argument, in which case rstrip removes characters found in x rather than removing whitespace.

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

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=None)

Returns a copy of s with both leading and trailing whitespace removed. Since Python 2.2.2, you can optionally pass a string x as an argument, in which case strip removes characters found in x rather than removing whitespace.

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='')

Returns a copy of s where all characters occurring in string deletechars are removed, and the remaining characters are mapped through translation-table table. When s is a plain string, table must be a plain string of length 256. When s is a Unicode string, table must be a Unicode string of length 65536. Each character c is mapped to character table[ord(c)]. A plain-string table is most often built using function string.maketrans, covered later.

upper

s.upper(  )

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

    Previous Section Next Section