Next / Previous / Contents / TCC Help System / NM Tech homepage

9.3. Methods on str values

These methods are available on any string value S.

S.capitalize()

Return S with its first character capitalized (if a letter).

>>> 'e e cummings'.capitalize()
'E e cummings'
>>> '---abc---'.capitalize()
'---abc---'

S.center(w)

Return S centered in a string of width w, padded with spaces. If w<=len(S), the result is a copy of S. If the number of spaces of padding is odd, the extra space will placed after the centered value. Example:

>>> 'x'.center(4)
' x  '
S.count(t[,start[,end]])

Return the number of times string t occurs in S. To search only a slice S[start:end] of S, supply start and end arguments.

>>> 'banana'.count('a')
3
>>> 'bananana'.count('na')
3
>>> 'banana'.count('a', 3)
2
>>> 'banana'.count('a', 3, 5)
1

S.decode ( encoding )

If S contains an encoded Unicode string, this method will return the corresponding value as unicode type. The encoding argument specifies which decoder to use; typically this will be the string 'utf_8' for the UTF-8 encoding. For discussion and examples, see Section 10.1, “The UTF-8 encoding”.

S.endswith(t[,start[,end]])

Predicate to test whether S ends with string t. If you supply the optional start and end arguments, it tests whether the slice S[start:end] ends with t.

>>> 'bishop'.endswith('shop')
True
>>> 'bishop'.endswith('bath and wells')
False
>>> 'bishop'[3:5]
'ho'
>>> 'bishop'.endswith('o', 3, 5)
True

S.expandtabs([tabsize])

Returns a copy of S with all tabs replaced by one or more spaces. Each tab is interpreted as a request to move to the next “tab stop”. The optional tabsize argument specifies the number of spaces between tab stops; the default is 8.

Here is how the function actually works. The characters of S are copied to a new string T one at a time. If the character is a tab, it is replaced by enough tabs so the new length of T is a multiple of the tab size (but always at least one space).

>>> 'X\tY\tZ'.expandtabs()
'X       Y       Z'
>>> 'X\tY\tZ'.expandtabs(4)
'X   Y   Z'
>>> 'a\tbb\tccc\tdddd\teeeee\tfffff'.expandtabs(4)
'a   bb  ccc dddd    eeeee   fffff'
S.find(t[,start[,end]])

If string t is not found in S, return -1; otherwise return the index of the first position in S that matches t.

The optional start and end arguments restrict the search to slice S[start:end].

>>> 'banana'.find('an')
1
>>> 'banana'.find('ape')
-1
>>> 'banana'.find('n', 3)
4
>>> 'council'.find('c', 1, 4)
-1

.format(*p, **kw)

See Section 9.4, “The string .format() method”.

S.index(t[,start[,end]])

Works like .find(), but if t is not found, it raises a ValueError exception.

>>> 'council'.index('co')
0
>>> 'council'.index('phd')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: substring not found

S.isalnum()

Predicate that tests whether S is nonempty and all its characters are alphanumeric.

>>> ''.isalnum()
False
>>> 'abc123'.isalnum()
True
>>> '&*$#&*()abc123'.isalnum()
False

S.isalpha()

Predicate that tests whether S is nonempty and all its characters are letters.

>>> 'abc123'.isalpha()
False
>>> 'MaryRecruiting'.isalpha()
True
>>> ''.isalpha()
False

S.isdigit()

Predicate that tests whether S is nonempty and all its characters are digits.

>>> 'abc123'.isdigit()
False
>>> ''.isdigit()
False
>>> '2415'.isdigit()
True

S.islower()

Predicate that tests whether S is nonempty and all its letters are lowercase (non-letter characters are ignored).

>>> ''.islower()
False
>>> 'abc123'.islower()
True
>>> 'ABC123'.islower()
False

S.isspace()

Predicate that tests whether S is nonempty and all its characters are whitespace characters.

>>> ''.isspace()
False
>>> ' \t\n\r'.isspace()
True
>>> 'killer \t \n rabbit'.isspace()
False
S.istitle()

A predicate that tests whether S has “title case”. In a title-cased string, uppercase characters may appear only at the beginning of the string or after some character that is not a letter. Lowercase characters may appear only after an uppercase letter.

>>> 'abc def GHI'.istitle()
False
>>> 'Abc Def Ghi'.istitle()
True

S.isupper()

Predicate that tests whether S is nonempty and all its letters are uppercase letters (non-letter characters are ignored).

>>> 'abcDEF'.isupper()
False
>>> '123GHI'.isupper()
True
>>> ''.isupper()
False

S.join(L)

L must be an iterable that produces a sequence of strings. The returned value is a string containing the members of the sequence with copies of the delimiter string S inserted between them.

One quite common operation is to use the empty string as the delimiter to concatenate the elements of a sequence.

Examples:

>>> '/'.join(['never', 'pay', 'plan'])
'never/pay/plan'
>>> '(***)'.join ( ('Property', 'of', 'the', 'zoo') )
'Property(***)of(***)the(***)zoo'
>>> ''.join(['anti', 'dis', 'establish', 'ment', 'arian', 'ism'])
'antidisestablishmentarianism'                

S.ljust(w)

Return a copy of S left-justified in a field of width w, padded with spaces. If w<=len(S), the result is a copy of S.

>>> "Ni".ljust(4)
'Ni  '

S.lower()

Returns a copy of S with all uppercase letters replaced by their lowercase equivalent.

>>> "I like SHOUTING!".lower()
'i like shouting!'

S.lstrip([c])

Return S with all leading characters from string c removed. The default value for c is a string containing all the whitespace characters.

>>> '  \t  \n Run \t \n away ! \n \t  '.lstrip()
'Run \t \n away ! \n \t  '
"***Done***".lstrip('*')
'Done***'
>>> "(*)(*)(*Undone*)".lstrip ( ")(*" )
'Undone*)'

S.partition(d)

Searches string S for the first occurrence of some delimiter string d. If S contains the delimiter, it returns a tuple (pre, d, post), where pre is the part of S before the delimiter, d is the delimiter itself, and post is the part of S after the delimiter.

If the delimiter is not found, this method returns a 3-tuple (S, '', '').

>>> "Daffy English kniggets!".partition(' ')
('Daffy', ' ', 'English kniggets!')
>>> "Daffy English kniggets!".partition('/')
('Daffy English kniggets!', '', '')
>>> "a*b***c*d".partition("**")
('a*b', '**', '*c*d')

S.replace(old,new[,max])

Return a copy of S with all occurrences of string old replaced by string new. Normally, all occurrences are replaced; if you want to limit the number of replacements, pass that limit as the max argument.

>>> 'Frenetic'.replace('e', 'x')
'Frxnxtic'
>>> 'Frenetic'.replace('e', '###')
'Fr###n###tic'
>>> 'banana'.replace('an', 'erzerk')
'berzerkerzerka'
>>> 'banana'.replace('a', 'x', 2)
'bxnxna'

S.rfind(t[,start[,end]])

Like .find(), but if t occurs in S, this method returns the highest starting index.

>>> 'banana'.find('a')
1
>>> 'banana'.rfind('a')
5

S.rindex(t[,start[,end]])

Similar to S.index(), but it returns the last index in S where string t is found. It will raise a ValueError exception if the string is not found.

>>> "Just a flesh wound.".index('s')
2
>>> "Just a flesh wound.".rindex('s')
10
>>> "Just a flesh wound.".rindex('xx')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: substring not found

S.rjust(w[,fill])

Return a copy of S right-justified in a field of width w, padded with spaces. If w<=len(S), the result is a copy of S.

To pad values with some character other than a space, pass that character as the optional second argument.

>>> '123'.rjust(5)
'  123'
>>> '123'.rjust(5,'*')
'**123'

S.rpartition(d)

Similar to S.partition(), except that it finds the last occurrence of the delimiter.

>>> "Daffy English kniggets!".rpartition(' ')
('Daffy English', ' ', 'kniggets!')
>>> "a*b***c*d".rpartition("**")
('a*b*', '**', 'c*d')

S.rsplit(d[,max])

Similar to S.split(d[,max]), except that if there are more fields than max, the split fields are taken from the end of the string instead of from the beginning.

>>> "I am Zoot's identical twin sister, Dingo.".rsplit(None, 2)
["I am Zoot's identical twin", 'sister,', 'Dingo.']

S.rstrip([c])

Return S with all trailing characters from string c removed. The default value for c is a string containing all the whitespace characters.

>>> '  \t  \n Run \t \n away ! \n \t  '.rstrip()
'  \t  \n Run \t \n away !'

S.split([d[,max]])

Returns a list of strings [s0, s1, ...] made by splitting S into pieces wherever the delimiter string d is found. The default is to split up S into pieces wherever clumps of one or more whitespace characters are found.

>>> "I'd annex \t \r the Sudetenland" .split()
["I'd", 'annex', 'the', 'Sudetenland']
>>> '3/crunchy frog/ Bath & Wells'.split('/')
['3', 'crunchy frog', ' Bath & Wells']
>>> '//Norwegian Blue/'.split('/')
['', '', 'Norwegian Blue', '']
>>> 'never<*>pay<*>plan<*>'.split('<*>')
['never', 'pay', 'plan', '']

The optional max argument limits the number of pieces removed from the front of S. The resulting list will have no more than max+1 elements.

To use the max argument while splitting the string on clumps of whitespace, pass None as the first argument.

>>> 'a/b/c/d/e'.split('/', 2)
['a', 'b', 'c/d/e']
>>> 'a/b'.split('/', 2)
['a', 'b']
>>> "I am Zoot's identical twin sister, Dingo.".split(None, 2)
['I', 'am', "Zoot's identical twin sister, Dingo."]

S.splitlines([keepends])

Splits S into lines and returns a list of the lines as strings. Discards the line separators unless the optional keepends arguments is true.

>>> """Is that
... an ocarina?""".splitlines()
['Is that', 'an ocarina?']
>>> """What is your name?
... Sir Robin of Camelot.""".splitlines(True)
['What is your name?\n', 'Sir Robin of Camelot.']

S.startswith(t[,start[,end]])

Predicate to test whether S starts with string t. Otherwise similar to .endswith().

>>> "bishop".startswith('bish')
True
>>> "bishop".startswith('The')
False

S.strip([c])

Return S with all leading and trailing characters from string c removed. The default value for c is a string containing all the whitespace characters.

>>> '  \t  \n Run \t \n away ! \n \t  '.strip()
'Run \t \n away !'

S.swapcase()

Return a copy of S with each lowercase character replaced by its uppercase equivalent, and vice versa.

>>> "abcDEF".swapcase()
'ABCdef'

S.title()

Returns the characters of S, except that the first letter of each word is uppercased, and other letters are lowercased.

>>> "huge...tracts of land".title()
'Huge...Tracts Of Land'

S.translate(new[,drop])

This function is used to translate or remove each character of S. The new argument is a string of exactly 256 characters, and each character x of the result is replaced by new[ord(x)].

If you would like certain characters removed from S before the translation, provide a string of those characters as the drop argument.

For your convenience in building the special 256-character strings used here, see the definition of the maketrans() function of Section 28.2, “string: Utility functions for strings”, where you will find examples.

S.upper()

Return a copy of S with all lowercase characters replaced by their uppercase equivalents.

>>> 'I like shouting'.upper()
'I LIKE SHOUTING'

S.zfill(w)

Return a copy of S left-filled with '0' characters to width w.

>>> '12'.zfill(9)
'000000012'