Tutorialspoint

1 Answer
Arushi

The string module in Python’s standard library provides following useful constants, classes and a helper function called capwords()

Constants

ascii_lettersThe concatenation of lowercase and uppercase constants.
ascii_lowercaseThe lowercase letters 'abcdefghijklmnopqrstuvwxyz'
ascii_uppercaseThe uppercase letters 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
digitsThe string '0123456789'.
hexdigitsThe string '0123456789abcdefABCDEF'.
octdigitsThe string '01234567'.
punctuationString of ASCII characters which are considered punctuation characters.
printableString of ASCII characters digits, ascii_letters, punctuation, andwhitespace.
whitespaceA string containing all ASCII characters that are consideredwhitespace such as space, tab, linefeed, return, formfeed, andvertical tab.

Output

>>> import string
>>> string.ascii_letters
'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
>>> string.ascii_lowercase
'abcdefghijklmnopqrstuvwxyz'
>>> string.ascii_uppercase
'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
>>> string.digits
'0123456789'
>>> string.hexdigits
'0123456789abcdefABCDEF'
>>> string.octdigits
'01234567'
>>> string.printable
'0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~ \t\n\r\x0b\x0c'
>>> string.punctuation
'!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'
>>> string.whitespace
' \t\n\r\x0b\x0c'

Capwords() function

This function performs following −

  • Splits the given string argument into words using str.split().

  • Capitalizes each word using str.capitalize()

  • and joins the capitalized words using str.join().

Example

>>> text='All animals are equal. Some are more equal'
>>> string.capwords(text)
'All Animals Are Equal. Some Are More Equal'

Formatter class

Python’s built-in str class has format() method using which string can be formatted. Formatter object behaves similarly. This may be useful to write customized formatter class by subclassing this Formatter class.

>>> from string import Formatter
>>> f=Formatter()
>>> f.format('name:{name}, age:{age}, marks:{marks}', name='Rahul', age=30, marks=50)
'name:Rahul, age:30, marks:50'

Template

This class is used to create a string template. It proves useful for simpler string substitutions.

>>> from string import Template
>>> text='My name is $name. I am $age years old'
>>> t=Template(text)
>>> t.substitute(name='Rahul', age=30)
'My name is Rahul. I am 30 years old'

Advertisements

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.