Trusted answers to developer questions

What is the whitespace constant in Python?

Get Started With Machine Learning

Learn the fundamentals of Machine Learning with this free course. Future-proof your career by adding ML skills to your toolkit — or prepare to land a job in AI or Data Science.

The string module

The string module in Python is a collection of different constants.

The whitespace constant

The whitespace constant in the string module contains the characters that are considered whitespace.

The value of the constant is as follows:

 \t\n\r\x0b\x0c

Syntax

string.whitespace

Since whitespace is a constant, we can access it via the string module.

Let’s look at two code examples that use the whitespace constant.

Example 1

import string
whitespace_output = string.whitespace
print("Hello")
print(whitespace_output)
print("World")

Explanation

  • Line 1: We import the string module.

  • Line 3: We store the output of string.whitespace in the whitespace_output variable.

  • Line 5: We print the whitespace_output variable.

Example 2

import string
def contains_whitespace(str_input):
for i in str_input:
if i in string.whitespace:
return True
return False
str_to_check_1 = "abjiaosfdgfRFDFD"
print("Does %s contain any whitespace? %s" % (str_to_check_1, contains_whitespace(str_to_check_1)))
str_to_check_2 = "abji232daosfdgfR. FDFD"
print("Does %s contain any whitespace? %s" % (str_to_check_2, contains_whitespace(str_to_check_2)))

Explanation

  • Line 1: We import the string module.

  • Lines 3–9: We define a function called contains_whitespace that accepts a string as its parameter. It also checks whether this string contains any whitespace characters or not.

  • Line 11: We define a string called str_to_check_1 with no whitespace characters.

  • Line 12: We invoke the contains_whitespace function by passing str_to_check_1 as the parameter.

  • Line 14: We define a string called str_to_check_2 containing whitespace characters.

  • Line 15: The contains_whitespace function is invoked passing str_to_check_2 as the parameter.

RELATED TAGS

python
Did you find this helpful?