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 , padded with spaces. If
w, the result is a copy of
w<=len(S).
If the number of spaces of padding is odd, the
extra space will placed after the centered
value. Example:
S
>>> 'x'.center(4) ' x '
S.count(t[,start[,end]])
Return the number of times string
occurs
in t. To
search only a slice S of S,
supply
S[start:end] and
start
arguments.
end
>>> 'banana'.count('a')
3
>>> 'bananana'.count('na')
3
>>> 'banana'.count('a', 3)
2
>>> 'banana'.count('a', 3, 5)
1
S.decode ( encoding )
If
contains an encoded Unicode string, this method will
return the corresponding value as Sunicode type. The argument specifies
which decoder to use; typically this will be the
string encoding'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 . If you supply the
optional
t and
start
arguments, it tests whether the slice
end ends
with S[start:end].
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 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 S argument
specifies the number of spaces between tab stops;
the default is 8.
tabsize
Here is how the function actually works. The
characters of are copied to a new string S 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).
T
>>> '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 is not found in
t, return
-1; otherwise return the index of the first
position in S that matches
S.
t
The optional and start
arguments restrict the search to slice end.
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)
S.index(t[,start[,end]])
Works like .find(), but if
is not
found, it raises a tValueError 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
is
nonempty and all its characters are alphanumeric.
S
>>> ''.isalnum() False >>> 'abc123'.isalnum() True >>> '&*$#&*()abc123'.isalnum() False
S.isalpha()
Predicate that
tests whether is nonempty and all its characters are
letters.
S
>>> 'abc123'.isalpha() False >>> 'MaryRecruiting'.isalpha() True >>> ''.isalpha() False
S.isdigit()
Predicate that
tests whether is nonempty and all its characters are
digits.
S
>>> 'abc123'.isdigit() False >>> ''.isdigit() False >>> '2415'.isdigit() True
S.islower()
Predicate
that tests whether
is nonempty and all its letters are lowercase
(non-letter characters are ignored).
S
>>> ''.islower() False >>> 'abc123'.islower() True >>> 'ABC123'.islower() False
S.isspace()
Predicate that
tests whether is nonempty and all its characters are
whitespace characters.
S
>>> ''.isspace() False >>> ' \t\n\r'.isspace() True >>> 'killer \t \n rabbit'.isspace() False
S.istitle()
A predicate
that tests whether has “Stitle 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 is nonempty and all its letters are
uppercase letters (non-letter characters are
ignored).
S
>>> 'abcDEF'.isupper() False >>> '123GHI'.isupper() True >>> ''.isupper() False
S.join(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 L inserted between them.
S
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 left-justified
in a field of width
S,
padded with spaces. If w, the result is a copy of
w<=len(S).
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 with all leading characters from string
S
removed. The default value for c is a
string containing all the whitespace
characters.
c
>>> ' \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 for the first
occurrence of some delimiter string S. If
d
contains the delimiter, it returns a tuple S(, where pre, d, post) is the
part of pre before the delimiter, S is the
delimiter itself, and d is the part of post after the
delimiter.
S
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 with all occurrences of
string S replaced by string old. Normally, all
occurrences are replaced; if you want to limit
the number of replacements, pass that limit as
the new argument.
max
>>> '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 occurs in
t,
this method returns the
highest starting index.
S
>>> 'banana'.find('a')
1
>>> 'banana'.rfind('a')
5
S.rindex(t[,start[,end]])
Similar to , but it returns the last index in S.index() where string S is
found. It will raise a tValueError
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 right-justified in a
field of width Sw, padded with
spaces. If , the result is a copy of w<=len(S).
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 , except that it finds the
last occurrence of the delimiter.
S.partition()
>>> "Daffy English kniggets!".rpartition(' ')
('Daffy English', ' ', 'kniggets!')
>>> "a*b***c*d".rpartition("**")
('a*b*', '**', 'c*d')
S.rsplit(d[,max])
Similar to ,
except that if there are more fields than S.split(d[,max]), the
split fields are taken from the end of the string
instead of from the beginning.
max
>>> "I am Zoot's identical twin sister, Dingo.".rsplit(None, 2) ["I am Zoot's identical twin", 'sister,', 'Dingo.']
S.rstrip([c])
Return
with all trailing characters from string S removed. The
default value for c is a string containing all the whitespace characters.
c
>>> ' \t \n Run \t \n away ! \n \t '.rstrip() ' \t \n Run \t \n away !'
S.split([d[,max]])
Returns a list of strings [ made by splitting s0,
s1,
...] into
pieces wherever the delimiter string S is found.
The default is to split up d into pieces wherever
clumps of one or more whitespace characters
are found.
S
>>> "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 argument limits the number of pieces removed
from the front of max. The resulting list will have no more than
S
elements.
max+1
To use the argument while splitting the string on
clumps of whitespace, pass maxNone 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 into lines and returns a list of the
lines as strings. Discards the line separators
unless the optional S arguments is
true.
keepends
>>> """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 . Otherwise similar
to t.endswith().
>>> "bishop".startswith('bish')
True
>>> "bishop".startswith('The')
False
S.strip([c])
Return with all leading and trailing
characters from string S removed. The default
value for c is a string containing all the whitespace
characters.
c
>>> ' \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 , except that the first
letter of each word is uppercased, and other
letters are lowercased.
S
>>> "huge...tracts of land".title() 'Huge...Tracts Of Land'
S.translate(new[,drop])
This function is used to translate or remove each
character of . The S argument is a string
of exactly 256 characters, and each character
new of
the result is replaced by xnew[ord(.
x)]
If you would like certain characters removed from
before the translation, provide a string of those
characters as the S argument.
drop
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 with all lowercase
characters replaced by their uppercase
equivalents.
S
>>> 'I like shouting'.upper() 'I LIKE SHOUTING'
S.zfill(w)
Return a copy of left-filled with S'0' characters to width .
w
>>> '12'.zfill(9) '000000012'