Section 6.6. String Built-in Methods


6.6. String Built-in Methods

String methods were added to Python in the 1.6 to 2.0 timeframethey also were added to Jython. These methods replace most of the functionality in the string module as well as to add new functionality. Table 6.6 shows all the current methods for strings. All string methods should fully support Unicode strings. Some are applicable only to Unicode strings.

Table 6.6. String Type Built-in Methods

Method Name

Description

string.capitalize()

Capitalizes first letter of string

string.center(width)

Returns a space-padded string with the original string centered to a total of width columns

string.count(str, beg= 0, end=len(string))

Counts how many times str occurs in string, or in a substring of string if starting index beg and ending index end are given

string.decode(encoding='UTF-8', errors='strict')

Returns decoded string version of string; on error, default is to raise a ValueError unless errors is given with 'ignore' or 'replace'

string.encode(encoding='UTF-8', errors='strict')[a]

Returns encoded string version of string; on error, default is to raise a ValueError unless errors is given with 'ignore' or 'replace'

string.endswith(obj, beg=0, end=len(string))[b],[e]

Determines if string or a substring of string (if starting index beg and ending index end are given) ends with obj where obj is typically a string; if obj is a tuple, then any of the strings in that tuple; returns true if so, and False otherwise

string.expandtabs(tabsize=8)

Expands tabs in string to multiple spaces; defaults to 8 spaces per tab if tabsize not provided

string.find(str, beg=0end=len(string))

Determine if str occurs in string, or in a substring of string if starting index beg and ending index end are given; returns index if found and -1 otherwise

string.index(str, beg=0, end=len(string))

Same as find(), but raises an exception if str not found

string.isalnum()[a],[b],[c]

Returns true if string has at least 1 character and all characters are alphanumeric and False otherwise

string.isalpha()[a],[b],[c]

Returns TRue if string has at least 1 character and all characters are alphabetic and False otherwise

string.isdecimal()[b],[c],[d]

Returns TRue if string contains only decimal digits and False otherwise

string.isdigit()[b],[c]

Returns true if string contains only digits and False otherwise

string.islower()[b],[c]

Returns true if string has at least 1 cased character and all cased characters are in lowercase and False otherwise

string.isnumeric()[b],[c],[d]

Returns true if string contains only numeric characters and False otherwise

string.isspace()[b],[c]

Returns true if string contains only whitespace characters and False otherwise

string.istitle()[b],[c]

Returns true if string is properly "titlecased" (see title()) and False otherwise

string.isupper()[b],[c]

Returns TRue if string has at least one cased character and all cased characters are in uppercase and False otherwise

string.join(seq)

Merges (concatenates) the string representations of elements in sequence seq into a string, with separator string

string.ljust(width)

Returns a space-padded string with the original string left-justified to a total of width columns

string.lower()

Converts all uppercase letters in string to lowercase

string.lstrip()

Removes all leading whitespace in string

string.partition(str)[e]

Like a combination of find() and split(), splits string into a 3-tuple (string_pre_str, str, string_post_str) on the first occurrence of str; if not found, string_pre_str == string

string.replace(str1, str2, num=string.count(str1))

Replaces all occurrences of str1 in string with str2, or at most num occurrences if num given

string.rfind(str, beg=0, end=len(string))

Same as find(), but search backward in string

string.rindex( str, beg=0, end=len(string))

Same as index(), but search backward in string

string.rjust(width)

Returns a space-padded string with the original string right-justified to a total of width columns

string.rpartition(str)[e]

Same as partition(), but search backwards in string

string.rstrip()

Removes all trailing whitespace of string

string.split(str="", num=string.count(str))

Splits string according to delimiter str (space if not provided) and returns list of substrings; split into at most num substrings if given

string.splitlines(num=string.count('\n'))[b],[c]

Splits string at all (or num) NEWLINEs and returns a list of each line with NEWLINEs removed

string.startswith(obj, beg=0, end=len(string))[b],[e]

Determines if string or a substring of string (if starting index beg and ending index end are given) starts with obj where obj is typically a string; if obj is a tuple, then any of the strings in that tuple; returns true if so, and False otherwise

string.strip([obj])

Performs both lstrip() and rstrip() on string

string.swapcase()

Inverts case for all letters in string

string.title()[b],[c]

Returns "titlecased" version of string, that is, all words begin with uppercase, and the rest are lowercase (also see istitle())

string.translate(str, del="")

Translates string according to translation table str (256 chars), removing those in the del string

string.upper()

Converts lowercase letters in string to uppercase

string.zfill(width)

Returns original string left-padded with zeros to a total of width characters; intended for numbers, zfill() retains any sign given (less one zero)


[a] Applicable to Unicode strings only in 1.6, but to all string types in 2.0.

[b] Not available as a string module function in 1.5.2.

[e] New or updated in Python 2.5.

[c] New in Jython 2.1.

[d] Applicable to Unicode strings only.

Some examples of using string methods:

>>> quest = 'what is your favorite color?' >>> quest.capitalize() 'What is your favorite color?' >>> >>> quest.center(40) '      what is your favorite color?      ' >>> >>> quest.count('or') 2 >>> >>> quest.endswith('blue') False >>> >>> quest.endswith('color?') True >>> >>> quest.find('or', 30) -1 >>> >>> quest.find('or', 22) 25 >> >>> quest.index('or', 10) 16 >>> >>> ':'.join(quest.split()) 'what:is:your:favorite:color?' >>> quest.replace('favorite color', 'quest') >>> 'what is your quest?' >>> >>> quest.upper() 'WHAT IS YOUR FAVORITE COLOR?'


The most complex example shown above is the one with split() and join(). We first call split() on our string, which, without an argument, will break apart our string using spaces as the delimiter. We then take this list of words and call join() to merge our words again, but with a new delimiter, the colon. Notice that we used the split() method for our string to turn it into a list, and then, we used the join() method for ':' to merge together the contents of the list.



Core Python Programming
Core Python Programming (2nd Edition)
ISBN: 0132269937
EAN: 2147483647
Year: 2004
Pages: 334
Authors: Wesley J Chun

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net