string.py 10.8 KB
Newer Older
1
"""A collection of string operations (most are no longer used in Python 1.6).
Guido van Rossum's avatar
Guido van Rossum committed
2

3 4 5 6
Warning: most of the code you see here isn't normally used nowadays.  With
Python 1.6, many of these functions are implemented as methods on the
standard string object. They used to be implemented by a built-in module
called strop, but strop is now obsolete itself.
7 8 9 10 11 12 13 14 15 16

Public module variables:

whitespace -- a string containing all characters considered whitespace
lowercase -- a string containing all characters considered lowercase letters
uppercase -- a string containing all characters considered uppercase letters
letters -- a string containing all characters considered letters
digits -- a string containing all characters considered decimal digits
hexdigits -- a string containing all characters considered hexadecimal digits
octdigits -- a string containing all characters considered octal digits
Fred Drake's avatar
Fred Drake committed
17 18
punctuation -- a string containing all characters considered punctuation
printable -- a string containing all characters considered printable
19 20 21

"""

Guido van Rossum's avatar
Guido van Rossum committed
22
# Some strings for ctype-style character classification
23
whitespace = ' \t\n\r\v\f'
Guido van Rossum's avatar
Guido van Rossum committed
24 25 26
lowercase = 'abcdefghijklmnopqrstuvwxyz'
uppercase = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
letters = lowercase + uppercase
27 28 29
ascii_lowercase = lowercase
ascii_uppercase = uppercase
ascii_letters = ascii_lowercase + ascii_uppercase
Guido van Rossum's avatar
Guido van Rossum committed
30 31 32
digits = '0123456789'
hexdigits = digits + 'abcdef' + 'ABCDEF'
octdigits = '01234567'
Tim Peters's avatar
Tim Peters committed
33
punctuation = """!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~"""
34
printable = digits + letters + punctuation + whitespace
Guido van Rossum's avatar
Guido van Rossum committed
35 36

# Case conversion helpers
37 38
_idmap = ''
for i in range(256): _idmap = _idmap + chr(i)
Guido van Rossum's avatar
Guido van Rossum committed
39 40
del i

41 42 43 44 45 46
# Backward compatible names for exceptions
index_error = ValueError
atoi_error = ValueError
atof_error = ValueError
atol_error = ValueError

Guido van Rossum's avatar
Guido van Rossum committed
47 48
# convert UPPER CASE letters to lower case
def lower(s):
49
    """lower(s) -> string
50

51
    Return a copy of the string s converted to lowercase.
52

53 54
    """
    return s.lower()
Guido van Rossum's avatar
Guido van Rossum committed
55 56 57

# Convert lower case letters to UPPER CASE
def upper(s):
58
    """upper(s) -> string
59

60
    Return a copy of the string s converted to uppercase.
61

62 63
    """
    return s.upper()
Guido van Rossum's avatar
Guido van Rossum committed
64 65 66

# Swap lower case letters and UPPER CASE
def swapcase(s):
67
    """swapcase(s) -> string
68

69 70
    Return a copy of the string s with upper case characters
    converted to lowercase and vice versa.
71

72 73
    """
    return s.swapcase()
Guido van Rossum's avatar
Guido van Rossum committed
74 75 76

# Strip leading and trailing tabs and spaces
def strip(s):
77
    """strip(s) -> string
78

79 80
    Return a copy of the string s with leading and trailing
    whitespace removed.
81

82 83
    """
    return s.strip()
Guido van Rossum's avatar
Guido van Rossum committed
84

85 86
# Strip leading tabs and spaces
def lstrip(s):
87
    """lstrip(s) -> string
88

89
    Return a copy of the string s with leading whitespace removed.
90

91 92
    """
    return s.lstrip()
93 94 95

# Strip trailing tabs and spaces
def rstrip(s):
96
    """rstrip(s) -> string
97

98 99
    Return a copy of the string s with trailing whitespace
    removed.
100

101 102
    """
    return s.rstrip()
103 104


Guido van Rossum's avatar
Guido van Rossum committed
105
# Split a string into a list of space/tab-separated words
106
def split(s, sep=None, maxsplit=-1):
107
    """split(s [,sep [,maxsplit]]) -> list of strings
108

109
    Return a list of the words in the string s, using sep as the
110
    delimiter string.  If maxsplit is given, splits into at most
111
    maxsplit words.  If sep is not specified, any whitespace string
112
    is a separator.
113

114
    (split and splitfields are synonymous)
115

116 117 118
    """
    return s.split(sep, maxsplit)
splitfields = split
119

120
# Join fields with optional separator
121 122
def join(words, sep = ' '):
    """join(list [,sep]) -> string
123

124
    Return a string composed of the words in list, with
125
    intervening occurrences of sep.  The default separator is a
126
    single space.
127

128
    (joinfields and join are synonymous)
129

130 131 132
    """
    return sep.join(words)
joinfields = join
133

134 135 136
# Find substring, raise exception if not found
def index(s, *args):
    """index(s, sub [,start [,end]]) -> int
137

138
    Like find but raises ValueError when the substring is not found.
139

140
    """
141
    return s.index(*args)
142

143
# Find last substring, raise exception if not found
144 145
def rindex(s, *args):
    """rindex(s, sub [,start [,end]]) -> int
146

147
    Like rfind but raises ValueError when the substring is not found.
148

149
    """
150
    return s.rindex(*args)
151 152

# Count non-overlapping occurrences of substring
153 154 155 156 157 158 159 160
def count(s, *args):
    """count(s, sub[, start[,end]]) -> int

    Return the number of occurrences of substring sub in string
    s[start:end].  Optional arguments start and end are
    interpreted as in slice notation.

    """
161
    return s.count(*args)
162

163
# Find substring, return -1 if not found
164 165 166 167 168 169 170 171 172 173
def find(s, *args):
    """find(s, sub [,start [,end]]) -> in

    Return the lowest index in s where substring sub is found,
    such that sub is contained within s[start,end].  Optional
    arguments start and end are interpreted as in slice notation.

    Return -1 on failure.

    """
174
    return s.find(*args)
Guido van Rossum's avatar
Guido van Rossum committed
175

176
# Find last substring, return -1 if not found
177 178 179 180 181 182 183 184 185 186
def rfind(s, *args):
    """rfind(s, sub [,start [,end]]) -> int

    Return the highest index in s where substring sub is found,
    such that sub is contained within s[start,end].  Optional
    arguments start and end are interpreted as in slice notation.

    Return -1 on failure.

    """
187
    return s.rfind(*args)
188 189 190 191 192 193

# for a bit of speed
_float = float
_int = int
_long = long
_StringType = type('')
194

195
# Convert string to float
196 197 198 199 200 201
def atof(s):
    """atof(s) -> float

    Return the floating point number represented by the string s.

    """
202 203
    return _float(s)

204

Guido van Rossum's avatar
Guido van Rossum committed
205
# Convert string to integer
206
def atoi(s , base=10):
207 208 209 210 211 212 213 214 215 216
    """atoi(s [,base]) -> int

    Return the integer represented by the string s in the given
    base, which defaults to 10.  The string s must consist of one
    or more digits, possibly preceded by a sign.  If base is 0, it
    is chosen from the leading characters of s, 0 for octal, 0x or
    0X for hexadecimal.  If base is 16, a preceding 0x or 0X is
    accepted.

    """
217
    return _int(s, base)
218

Guido van Rossum's avatar
Guido van Rossum committed
219

220
# Convert string to long integer
221
def atol(s, base=10):
222 223 224 225 226 227 228 229 230 231 232
    """atol(s [,base]) -> long

    Return the long integer represented by the string s in the
    given base, which defaults to 10.  The string s must consist
    of one or more digits, possibly preceded by a sign.  If base
    is 0, it is chosen from the leading characters of s, 0 for
    octal, 0x or 0X for hexadecimal.  If base is 16, a preceding
    0x or 0X is accepted.  A trailing L or l is not accepted,
    unless base is 0.

    """
233
    return _long(s, base)
234

235

Guido van Rossum's avatar
Guido van Rossum committed
236 237
# Left-justify a string
def ljust(s, width):
238
    """ljust(s, width) -> string
239

240 241 242
    Return a left-justified version of s, in a field of the
    specified width, padded with spaces as needed.  The string is
    never truncated.
243

244
    """
245
    return s.ljust(width)
Guido van Rossum's avatar
Guido van Rossum committed
246 247 248

# Right-justify a string
def rjust(s, width):
249
    """rjust(s, width) -> string
250

251 252 253
    Return a right-justified version of s, in a field of the
    specified width, padded with spaces as needed.  The string is
    never truncated.
254

255
    """
256
    return s.rjust(width)
Guido van Rossum's avatar
Guido van Rossum committed
257 258 259

# Center a string
def center(s, width):
260
    """center(s, width) -> string
261

262 263 264
    Return a center version of s, in a field of the specified
    width. padded with spaces as needed.  The string is never
    truncated.
265

266
    """
267
    return s.center(width)
Guido van Rossum's avatar
Guido van Rossum committed
268 269 270 271 272

# Zero-fill a number, e.g., (12, 3) --> '012' and (-3, 3) --> '-03'
# Decadent feature: the argument may be a string or a number
# (Use of this is deprecated; it should be a string as with ljust c.s.)
def zfill(x, width):
273
    """zfill(x, width) -> string
274

275 276
    Pad a numeric string x with zeros on the left, to fill a field
    of the specified width.  The string x is never truncated.
277

278 279 280 281 282 283 284
    """
    if type(x) == type(''): s = x
    else: s = `x`
    n = len(s)
    if n >= width: return s
    sign = ''
    if s[0] in ('-', '+'):
Fred Drake's avatar
Fred Drake committed
285
        sign, s = s[0], s[1:]
286
    return sign + '0'*(width-n) + s
287 288 289

# Expand tabs in a string.
# Doesn't take non-printing chars into account, but does understand \n.
Guido van Rossum's avatar
Guido van Rossum committed
290
def expandtabs(s, tabsize=8):
291 292 293 294 295 296 297
    """expandtabs(s [,tabsize]) -> string

    Return a copy of the string s with all tab characters replaced
    by the appropriate number of spaces, depending on the current
    column, and the tabsize (default 8).

    """
298
    return s.expandtabs(tabsize)
299

300
# Character translation through look-up table.
301
def translate(s, table, deletions=""):
302
    """translate(s,table [,deletions]) -> string
303 304

    Return a copy of the string s, where all characters occurring
305
    in the optional argument deletions are removed, and the
306
    remaining characters have been mapped through the given
307 308
    translation table, which must be a string of length 256.  The
    deletions argument is not allowed for Unicode strings.
309 310

    """
311 312 313 314 315 316 317
    if deletions:
        return s.translate(table, deletions)
    else:
        # Add s[:0] so that if s is Unicode and table is an 8-bit string,
        # table is converted to Unicode.  This means that table *cannot*
        # be a dictionary -- for that feature, use u.translate() directly.
        return s.translate(table + s[:0])
318

319 320
# Capitalize a string, e.g. "aBc  dEf" -> "Abc  def".
def capitalize(s):
321
    """capitalize(s) -> string
322

323 324
    Return a copy of the string s with only its first character
    capitalized.
325

326 327
    """
    return s.capitalize()
328 329 330

# Capitalize the words in a string, e.g. " aBc  dEf " -> "Abc Def".
# See also regsub.capwords().
331
def capwords(s, sep=None):
332
    """capwords(s, [sep]) -> string
333

334 335 336 337
    Split the argument into words using split, capitalize each
    word using capitalize, and join the capitalized words using
    join. Note that this replaces runs of whitespace characters by
    a single space.
338

339 340
    """
    return join(map(capitalize, s.split(sep)), sep or ' ')
341

342 343 344
# Construct a translation string
_idmapL = None
def maketrans(fromstr, tostr):
345 346 347 348 349 350 351 352
    """maketrans(frm, to) -> string

    Return a translation table (a string of 256 bytes long)
    suitable for use in string.translate.  The strings frm and to
    must be of the same length.

    """
    if len(fromstr) != len(tostr):
Fred Drake's avatar
Fred Drake committed
353
        raise ValueError, "maketrans arguments must have same length"
354 355
    global _idmapL
    if not _idmapL:
Fred Drake's avatar
Fred Drake committed
356
        _idmapL = map(None, _idmap)
357 358 359
    L = _idmapL[:]
    fromstr = map(ord, fromstr)
    for i in range(len(fromstr)):
Fred Drake's avatar
Fred Drake committed
360
        L[fromstr[i]] = tostr[i]
361
    return join(L, "")
362

363
# Substring replacement (global)
364
def replace(s, old, new, maxsplit=-1):
365
    """replace (str, old, new[, maxsplit]) -> string
366

367 368 369
    Return a copy of string str with all occurrences of substring
    old replaced by new. If the optional argument maxsplit is
    given, only the first maxsplit occurrences are replaced.
370

371 372
    """
    return s.replace(old, new, maxsplit)
373 374


375 376
# Try importing optional built-in module "strop" -- if it exists,
# it redefines some string operations that are 100-1000 times faster.
377 378
# It also defines values for whitespace, lowercase and uppercase
# that match <ctype.h>'s definitions.
379 380

try:
381 382
    from strop import maketrans, lowercase, uppercase, whitespace
    letters = lowercase + uppercase
383
except ImportError:
Fred Drake's avatar
Fred Drake committed
384
    pass                                          # Use the original versions