Common string operations in Python

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


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.


>>> import string
>>> string.ascii_letters
>>> string.ascii_lowercase
>>> string.ascii_uppercase
>>> string.digits
>>> string.hexdigits
>>> string.octdigits
>>> 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().


>>> 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'


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'

Updated on: 30-Jul-2019


Kickstart Your Career

Get certified by completing the course

Get Started