Last Updated : 11 Jul, 2025
In Python, string.whitespace is a string containing all the characters that are considered whitespace. Whitespace characters include spaces, tabs, newlines and other characters that create space in text. string.whitespace constant is part of the string module, which provides a collection of string operations and constants.
Let's understand with an example:
Python
import string
s = "Hello\tWorld\n"
whitespace = [i for i in s if i in string.whitespace]
print(whitespace)
Explanation: In this example, the code identifies the tab (\t) and newline (\n) characters as whitespace in the given text.
Syntax of string.whitespaceThe string.whitespace is simply a predefined constant in the string module. We can access it directly from the module as follows:
Parametersprint(string.whitespace)
string
module.Whitespace characters often need to be removed from input strings for data processing.
Python
import string
s = "\tHello World!\n"
# Removing all whitespace characters
cleaned = ''.join(char for char in s if char not in string.whitespace)
print(cleaned)
Explanation
We can use string.whitespace to ensure a string contains meaningful content.
Python
import string
def is_non_empty(s):
return any(char not in string.whitespace for char in s)
print(is_non_empty("\t \n"))
print(is_non_empty("Python\n"))
Explanation
Counting whitespace characters can be done using the generator expression, let's see how:
Python
import string
s = "Python\tProgramming\nIs Fun"
# Counting whitespace characters
count = sum(1 for char in s if char in string.whitespace)
print(count)
Explanation
Let's see how we can split a string by whitespace characters.
Python
import string
s = "Hello\tPython\nWorld"
# Splitting the string using whitespace characters
split_text = ''.join(char if char not in string.whitespace else ' ' for char in s).split()
print(split_text)
['Hello', 'Python', 'World']Explanation
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4