Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
string.whitespace in Python
In this tutorial, we are going to learn about string.whitespace in Python. The string.whitespace constant is pre-defined in the string module and contains all ASCII whitespace characters: space, tab, linefeed, return, formfeed, and vertical tab.
What is string.whitespace?
The string.whitespace is a string constant that contains all characters considered as whitespace in ASCII. This includes:
- Space character (' ')
- Tab character ('\t')
- Newline character ('\n')
- Carriage return ('\r')
- Form feed ('\f')
- Vertical tab ('\v')
Basic Example
Let's see what string.whitespace contains ?
import string
print("Content of string.whitespace:")
print(repr(string.whitespace))
print("\nLength:", len(string.whitespace))
Content of string.whitespace: ' \t\n\r\x0b\x0c' Length: 6
Practical Use Cases
Checking if a Character is Whitespace
You can use string.whitespace to check if a character is a whitespace character ?
import string
characters = ['a', ' ', '\t', '\n', '5', '\r']
for char in characters:
if char in string.whitespace:
print(f"'{repr(char)}' is whitespace")
else:
print(f"'{char}' is not whitespace")
'a' is not whitespace ' ' is whitespace '\t' is whitespace '\n' is whitespace '5' is not whitespace '\r' is whitespace
Removing Whitespace Characters
Use string.whitespace to remove all whitespace characters from a string ?
import string
text = "Hello\t World\n\r Python"
print("Original text:", repr(text))
# Remove all whitespace characters
cleaned_text = ''.join(char for char in text if char not in string.whitespace)
print("Cleaned text:", cleaned_text)
Original text: 'Hello\t World\n\r Python' Cleaned text: HelloWorldPython
Comparison with Other Methods
| Method | Purpose | Example |
|---|---|---|
string.whitespace |
All ASCII whitespace | Custom whitespace operations |
str.isspace() |
Check if string is whitespace | ' \t'.isspace() |
str.strip() |
Remove leading/trailing whitespace | ' text '.strip() |
Conclusion
string.whitespace is a useful constant for custom whitespace detection and manipulation. It contains all ASCII whitespace characters and is particularly helpful when you need more control than built-in string methods provide.
