string
moduleThe string
module in Python is a collection of different constants.
whitespace
constantThe 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
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.
import stringwhitespace_output = string.whitespaceprint("Hello")print(whitespace_output)print("World")
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.
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)))
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.