What is the whitespace constant in Python?
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 stringwhitespace_output = string.whitespaceprint("Hello")print(whitespace_output)print("World")
Explanation
-
Line 1: We import the
stringmodule. -
Line 3: We store the output of
string.whitespacein thewhitespace_outputvariable. -
Line 5: We print the
whitespace_outputvariable.
Example 2
import stringdef contains_whitespace(str_input):for i in str_input:if i in string.whitespace:return Truereturn Falsestr_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
stringmodule. -
Lines 3–9: We define a function called
contains_whitespacethat 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_1with no whitespace characters. -
Line 12: We invoke the
contains_whitespacefunction by passingstr_to_check_1as the parameter. -
Line 14: We define a string called
str_to_check_2containing whitespace characters. -
Line 15: The
contains_whitespacefunction is invoked passingstr_to_check_2as the parameter.