O'Reilly logo

Python in a Nutshell, 2nd Edition by Alex Martelli

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Methods of String Objects

Plain and Unicode strings are immutable sequences, as covered in Strings. 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. See also Locale Sensitivity.

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 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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required