The string module is a part of Python's standard library and provides several helpful utilities for working with strings. From predefined sets of characters (such as ASCII letters, digits and punctuation) to useful functions for string formatting and manipulation, the string module streamlines various string operations that are commonly encountered in programming.
Note: The Python String module is a part of the standard Python library, so we do not need to explicitly install it.
Key features:
- Validation: Check if characters in a string belong to specific sets.
- Formatting: Format strings for better output or presentation.
- Template Handling: Create templates with placeholders that can be dynamically filled.
To begin using the string module, we can simply import it into our Python program:
import string
Functions in the Python String Module
In addition to constants, the string module provides several useful functions that simplify string manipulation.
1. capwords()
capwords() capitalizes the first letter of each word in a string and makes the rest lowercase, while collapsing multiple spaces between words into a single space.
Example:
Python
import string
s = "hello, geek! this is your geeksforgeeks!"
print(string.capwords(s))
OutputHello, Geek! This Is Your Geeksforgeeks!
Explanation: string.capwords() function splits the input string s into words by spaces, capitalizes the first letter of each word and then joins the words back together into a single string. It doesn't affect punctuation marks, which remain in their original position.
2. Formatter()
Formatter class allows custom string formatting. It works behind the scenes in Python’s str.format() method but can be extended for more complex formatting needs.
Python
from string import Formatter
fmt = Formatter()
print(fmt.format("Hello, {}!", "geek"))
Explanation: fmt.format() insert values into a string using placeholders marked by curly braces {}. In this case, the string "Hello, {}!" contains a placeholder {}, which is replaced by the argument "geek".
3. Template()
Template class is useful for creating string templates with placeholders that can be substituted with dynamic data. It has a substitute() method and a safer safe_substitute() method that doesn't raise an error if a placeholder is missing.
Python
from string import Template
s = Template("Hello, $name!")
print(s.substitute(name="geek"))
print(s.safe_substitute(name="Python"))
print(s.safe_substitute())
OutputHello, geek!
Hello, Python!
Hello, $name!
Explanation: substitute() replaces placeholders with provided values, while safe_substitute() does the same but doesn't raise an error if a placeholder is missing, using a default value instead. If no value is given, safe_substitute() returns the original string.
Constants in the Python String
Module
The string module provides several constants that represent commonly used sets of characters. These constants can be helpful for validating, cleaning, or manipulating strings efficiently.
Constant | Description | Example Output |
---|
ascii_letters | All ASCII letters, both lowercase and uppercase. | abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ |
---|
ascii_lowercase | All lowercase ASCII letters. | abcdefghijklmnopqrstuvwxyz |
---|
ascii_uppercase | All uppercase ASCII letters. | ABCDEFGHIJKLMNOPQRSTUVWXYZ |
---|
digits | All decimal digits (0-9). | 0123456789 |
---|
hexdigits | All characters used in hexadecimal numbers (0-9 and A-F). | 0123456789abcdefABCDEF |
---|
octdigits | All characters used in octal numbers (0-7). | 01234567 |
---|
punctuation | All punctuation marks. | !"#$%&'()*+,-./:;<=>?@[\]^_{ |
---|
printable | All printable characters, including letters, digits, punctuation, and whitespace. | 0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&'()*+,-./:;<=>?@[\]^_{ |
---|
whitespace | All characters considered whitespace, such as spaces, tabs, and newlines. | " \t\n\r\x0b\x0c" |
---|
Real-World Use Cases of the Python String Module
Let’s explore a few practical scenarios where the Python string module can simplify our tasks.
1. Validate User Input Data
The string module helps with input validation, such as checking if a string consists only of digits or alphabetic characters.
Python
import string
def fun(s):
return all(char in string.digits for char in s)
print(fun("12345"))
print(fun("123a5"))
Explanation: fun(s) function checks if all characters in the string s are digits using string.digits and the all() function. It returns True if all characters are digits, otherwise False.
2. Custom formatting
Using Formatter(), we can create custom string formats to convert numbers into specific formats or create custom messages.
Python
from string import Formatter
def fun(number):
return f"The number is: {number:.2f}"
print(fun(123.456))
OutputThe number is: 123.46
Explanation: fun(number) that formats a floating-point number to display two decimal places. It uses an f-string with the format specifier :.2f, which ensures that the number is rounded to two decimal places.
3. Parsing data files
When parsing data files (like logs), Template can simplify the process by allowing dynamic substitution of values into predefined strings.
Python
from string import Template
log_temp = Template("User: $user, Action: $action")
res = log_temp.safe_substitute(user="Geek", action="Login")
print(res)
OutputUser: Geek, Action: Login
Explanation: log_temp string contains placeholders $user and $action. The safe_substitute() method replaces these placeholders with the values provided (user="Geek" and action="Login") without raising an error if any placeholder is missing.
Similar Reads
Python Tutorial | Learn Python Programming Language
Python Tutorial â Python is one of the most popular programming languages. Itâs simple to use, packed with features and supported by a wide range of libraries and frameworks. Its clean syntax makes it beginner-friendly. Python is: A high-level language, used in web development, data science, automat
10 min read
Python Interview Questions and Answers
Python is the most used language in top companies such as Intel, IBM, NASA, Pixar, Netflix, Facebook, JP Morgan Chase, Spotify and many more because of its simplicity and powerful libraries. To crack their Online Assessment and Interview Rounds as a Python developer, we need to master important Pyth
15+ min read
Python OOPs Concepts
Object Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications. By understanding the core OOP principles (classes, objects, inheritance, encapsulation, polymorphism, and abstraction), programmers can leverage the full p
11 min read
Python Projects - Beginner to Advanced
Python is one of the most popular programming languages due to its simplicity, versatility, and supportive community. Whether youâre a beginner eager to learn the basics or an experienced programmer looking to challenge your skills, there are countless Python projects to help you grow. Hereâs a list
10 min read
Python Exercise with Practice Questions and Solutions
Python Exercise for Beginner: Practice makes perfect in everything, and this is especially true when learning Python. If you're a beginner, regularly practicing Python exercises will build your confidence and sharpen your skills. To help you improve, try these Python exercises with solutions to test
9 min read
Python Programs
Practice with Python program examples is always a good choice to scale up your logical understanding and programming skills and this article will provide you with the best sets of Python code examples. The below Python section contains a wide collection of Python programming examples. These Python c
11 min read
Python Data Types
Python Data types are the classification or categorization of data items. It represents the kind of value that tells what operations can be performed on a particular data. Since everything is an object in Python programming, Python data types are classes and variables are instances (objects) of thes
10 min read
Enumerate() in Python
enumerate() function adds a counter to each item in a list or other iterable. It turns the iterable into something we can loop through, where each item comes with its number (starting from 0 by default). We can also turn it into a list of (number, item) pairs using list(). Let's look at a simple exa
3 min read
Python Lists
In Python, a list is a built-in dynamic sized array (automatically grows and shrinks). We can store all types of items (including another list) in a list. A list may contain mixed type of items, this is possible because a list mainly stores references at contiguous locations and actual items maybe s
6 min read
Dictionaries in Python
A Python dictionary is a data structure that stores the value in key: value pairs. Values in a dictionary can be of any data type and can be duplicated, whereas keys can't be repeated and must be immutable. Example: Here, The data is stored in key:value pairs in dictionaries, which makes it easier t
5 min read