May 2001
Intermediate to advanced
304 pages
6h 12m
English
The string module contains a number of functions to process standard Python
strings, as shown in Example 1-51.
Example 1-51. Using the string Module
File: string-example-1.py import string text = "Monty Python's Flying Circus" print "upper", "=>", string.upper(text) print "lower", "=>", string.lower(text) print "split", "=>", string.split(text) print "join", "=>", string.join(string.split(text), "+") print "replace", "=>", string.replace(text, "Python", "Java") print "find", "=>", string.find(text, "Python"), string.find(text, "Java") print "count", "=>", string.count(text, "n")upper => MONTY PYTHON'S FLYING CIRCUSlower => monty python's flying circussplit => ['Monty', "Python's", 'Flying', 'Circus']join => Monty+Python's+Flying+Circusreplace => Monty Java's Flying Circusfind => 6 -1count => 3
In Python 1.5.2 and earlier, the string module uses functions from the
strop
implementation module where possible.
In Python 1.6 and later, most string operations are made available as
string methods as well, as shown in Example 1-52. Many of the functions in the
string module are simply wrapper functions that
call the corresponding string method.
Example 1-52. Using string Methods Instead of string Module Functions
File: string-example-2.py text = "Monty Python's Flying Circus" print "upper", "=>", text.upper() print "lower", "=>", text.lower() print "split", "=>", text.split() print "join", "=>", "+".join(text.split()) print "replace", "=>", text.replace("Python", "Perl") ...Read now
Unlock full access