Next / Previous / Contents / TCC Help System / NM Tech homepage

20.4. The string module

This module contains additional features for manipulating strings.

20.4.1. Variables in the string module

Variables defined in the string module include:

digits

The string "0123456789".

lowercase

A string containing all the lowercase letters, "abcdefghijklmnopqrstuvwxyz".

uppercase

A string containing all the uppercase letters, "ABCDEFGHIJKLMNOPQRSTUVWXYZ".

letters

The concatenation of lowercase and uppercase.

punctuation

String of characters that are considered punctuation marks: ! " # $ % & ' ( ) * + , - . / : ; < = > ? @ [ \ ] ^ _ ` { | } ~

whitespace

Characters considered whitespace, generally " \t\n\r\f\v".

printable

String containing all the printable characters, the union of letters, digits, punctuation, and whitespace.

octdigits

The string "01234567".

hexdigits

"0123456789abcdefABCDEF".

20.4.2. Functions in the string module

In addition to the variables and functions in this module, there are a large number of functions that duplicate the built-in methods on strings. For example, instead of

s.split(",", 1)

you can get the same function with

import string
string.split(s, ",", 1)

In general, for any built-in method

s.m(arg1,arg2,...),

you can import the string module and get the same effect with

string.m(s,arg1,arg2,...),

Additional functions include:

maketrans(s,t)

Builds a translation table to be used as the first argument to the S.translate() string method. The arguments s and t are two strings of the same length; the result is a translation table that will convert each character of s to the corresponding character of t.

Here's an example:

>>> import string
>>> bingo=string.maketrans("lLrR", "rRlL")
>>> "Cornwall Llanfair".translate(bingo)
'Colnwarr Rranfail'
join(L[,d])

L must be a sequence. Returns a string containing the members of the sequence with copies of string d inserted between them. The default value of d is one space. For example, string.join(['baked', 'beans, 'are', 'off']) returns the string 'baked beans are off'.