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

Get Python in a Nutshell, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.