A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.geeksforgeeks.org/python/string-whitespace-in-python/ below:

string.whitespace in Python - GeeksforGeeks

string.whitespace in Python

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.whitespace

The string.whitespace is simply a predefined constant in the string module. We can access it directly from the module as follows:

print(string.whitespace)

Parameters Return Type Examples of string.whitespace in Python 1. Removing whitespace from a string

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 2. Validating strings for non-whitespace content

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 3. Counting whitespace characters in a string

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 4. Splitting a string by whitespace characters

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)  

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