Hello Python lovers, In today’s article, we are about to learn the Python string module which is a Python built-in module you don’t need to install it by using Python PIP command by default it comes with Python itself. If you want to work with special characters, upper cases, and lower cases in your Python application then the string module will be best for you.
To understand this example you should have basic knowledge of Python Programming.
Now, Let’s explore all about the string module in Python and their use cases along with their features.
Headings of Contents
Python String Module:
Python provides a built-in module named string which provides lots of functions and properties to precess the string. There is no need for the installation of a string module and you can just import it in your Python application and start using it.
Key Features of the String Module
There are some key features available in the Python string module.
- String Constants
- Custom String Templates
- Useful String Functions
String Constants:
Python string module provides some groups of strong contacts for common use cases. All the pre-defined string constants are listed below.
- ascii_letters: Concatenation of
ascii_lowercase
andascii_uppercase
. - ascii_lowercase: All lowercase letters (a-z).
- ascii_uppercase: All uppercase letters (A-Z).
- digits: All decimal digits (0-9).
- punctuation: Common punctuation symbols.
- printable: Combination of ascii_letters, digits, punctuations and whitespace
Let’s have a look at the constants, defined in the string module.
string.ascii_letters
This constants return the combination of ascii.lowercase and ascii.uppercase letters.
import string
x = string.ascii_letters
print(x)
Output
abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
string.ascii_lowercase:
string.ascii_lowercase constants return the lowercase letters.
import string
x = string.ascii_lowercase
print(x)
Output
abcdefghijklmnopqrstuvwxyz
string.ascii_uppercase:
string.ascii_uppercase constants return the upper case letters.
import string
x = string.ascii_uppercase
print(x)
Output
ABCDEFGHIJKLMNOPQRSTUVWXYZ
string.digits:
The string.digits constant returns the digits.
import string
x = string.digits
print(x)
Output
0123456789
string.hexdigits:
The string.hexdigits return the hexadecimal:
import string
x = string.hexdigits
print(x)
Output
0123456789abcdefABCDEF
string.octdigits:
The string.octdigits return the hexadecimal.
import string
x = string.hexdigits
print(x)
Output will be:- 01234567
string.punctuation:
The string.punctuation return the punctuations.
import string
x = string.punctuation
print(x)
Output
!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~
string.whitespace:
The string.whitespace return the whitespaces.
import string
x = string.whitespace
print(x)
string.printable:
The string.printable constants return the combination of ascii_letters, digits, punctuations and whitespace.
import string
x = string.printable
print(x)
Output
0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~
Constants Use Case:
All the above constants can be used for string processing, generating random strings, validating string,s and stripping invalid characters from text.
Python string module Helper Function:
The string module also provides some functions to manipulate the string.
capwords(s, sep = None)
The string.capwords() helper function is used to split the string into the words using str.split() function. Then it capitalizes each word using str.capitalize() function. Finally, It joins the capitalized words using str.join().
Example 1:
import string
txt = "Programming Funda is programming portal"
x = string.capwords(txt)
print(x)
Output will be:- Programming Funda Is Programming Portal
Example 2:
import string
txt = " Programming Funda is programming portal "
x = string.capwords(txt, "g")
print(x)
Output
progRamming funda is progRamming portal
Use Case:
Useful when formatting titles, headings, or proper names where each word needs to start with a capital letter.
Python string Module Classes:
Python built-in string module provide two class Formatter and Template which can be also used for string manipulation but in different ways.
Formatter Class:
The string module Formatter class allows us to create a string with placeholders that can be replaced with actual values. The Formatter class is used to format the string the same as the str.format() function.
from string import Formatter
formatter = Formatter()
print(formatter.format('{portal}', portal = 'ProgrammingFunda is a portal'))
print(formatter.format('{} {portal}', 'Programming Funda', portal = 'is a programming portal'))
print('{} {portal}'.format('Welcome to the', portal = 'programming Funda'))
Output
ProgrammingFunda is a portal
Programming Funda is a programming portal
Welcome to the programming Funda
Use Case:
When creating templated strings such as HTML templates, emails, or notification messages, using placeholders that are replaced with values dynamically.
Template Class:
Template class is used to create the string template for simple string substitute. The Template provides more complex string formatting rather than Formatter class.
from string import Template
temp = Template("$name is the Founder of $portal")
s = temp.substitute(name = "Vishvajit Rao", portal = "Programming Funda")
print(s)
Output
Vishvajit Rao is the Founder of Programming Funda
User Case:
You can use this Template class to create complex formatted text, such as dynamically generating reports or messages with a flexible structure.
Python string Module Real Word use Cases
It’s very mandatory to know where string module can be used in real-world Python application, let’s see this, I have listed two real world use cases of string module in Python.
Random Password Generator
We can generate secure password with the help of the Python string module. Here, I am going to create a random password by combination of lower case, upper case and special characters.
import random import string def generate_password(length=8): characters = string.ascii_letters + string.digits + string.punctuation password = '' for i in range(length): password = password + random.choice(characters) return password print(generate_password(12))
Each time we will get a random password like fFh[d)u.4wK and if you will not provide length of password during the calling generate_password() function it will automatically generate password of eight characters.
Validating Input for Specific Characters
Using constants like digits
or punctuation
, you can easily check if a string contains only valid characters.
import string def is_valid_number(input_str): return all(char in string.digits for char in input_str) print(is_valid_number("12345")) # True print(is_valid_number("123a5")) # False
This is how you can use string module in Python in order to work for string processing.
You will become more aware of the String module as you use it.
Recommended Articles:
- Python Platform Module
- Python HTML Module
- Python base64 Module
- Python DateTime Module
- Python Array Module
- Python Time Module
- Python collections module
- Python calendar module
- Python itertools module
Conclusion:
So throughout this article, We have seen all about the Python string module. The string module in Python provides lots of predefined constants functions that are used to process the string.
If you are planning to work with string in your Python project and where you want to valid string, remove invalid characters from text, generate random string, etc then Python string moule van be a good choice for you.
I hope this tutorial will help you, If you found this article helpful, Please comment and share with your friends who want to learn Python programming from scratch to advanced.
For More Information:- Click Here
This article was written and verified by Vishvajit Rao.