View Discussion
Improve Article
Save Article
View Discussion
Improve Article
Save Article
In Python3, string.whitespace
is a pre-initialized string used as string constant. In Python, string.whitespace
will give the characters space, tab,
linefeed, return, formfeed, and vertical tab.
Syntax : string.whitespace
Parameters : Doesn’t take any parameter, since it’s not a function.
Returns : Return the characters space, tab, linefeed, return, formfeed, and vertical tab.
Note : Make sure to import string library function inorder to use string.whitespace
Code #1 :
import
string
print
[
"Hello"
]
result
=
string.whitespace
print
[result]
print
[
"Geeksforgeeks"
]
Output:
Hello Geeksforgeeks
Code #2 : Given code tests for the whitespace values.
import
string
Sentence
=
"Hey, Geeks !, How are you?"
for
i
in
Sentence:
if
i
in
string.whitespace:
print
[
"printable Value is: "
+
i]
Output:
printable Value is: printable Value is: printable Value is: printable Value is: printable Value is:
View Discussion
Improve Article
Save Article
View Discussion
Improve Article
Save Article
Python String isspace[] method returns “True” if all characters in the string are whitespace characters, Otherwise, It returns “False”. This function is used to check if the argument contains all whitespace characters, such as:
- ‘ ‘ – Space
- ‘\t’ – Horizontal tab
- ‘\n’ – Newline
- ‘\v’ – Vertical tab
- ‘\f’ – Feed
- ‘\r’ – Carriage return
Python String isspace[] Method Syntax
Syntax: string.isspace[]
Returns:
- True – If all characters in the string are whitespace characters.
- False – If the string contains 1 or more non-whitespace characters.
Python String isspace[] Method Example
Python3
string
=
"\n\t\n"
print
[string.isspace[]]
Output:
True
Example 1: Basic Intuition of isspace[] in Program
Here we will check whitespace in the string using isspace[] program.
Python3
string
=
'Geeksforgeeks'
print
[string.isspace[]]
string
=
'\n \n \n'
print
[string.isspace[]]
string
=
'Geeks\nfor\ngeeks'
print
[ string.isspace[]]
Output:
False True False
Example 2: Practical Application
Given a string in Python, count the number of whitespace characters in the string.
Input : string = 'My name is Ayush' Output : 3 Input : string = 'My name is \n\n\n\n\nAyush' Output : 8
Algorithm:
- Traverse the given string character by character up to its length, check if the character is a whitespace character.
- If it is a whitespace character, increment the counter by 1, else traverse to the next character.
- Print the value of the counter.
Python3
string
=
'My name is Ayush'
count
=
0
for
a
in
string:
if
[a.isspace[]]
=
=
True
:
count
+
=
1
print
[count]
string
=
'My name is \n\n\n\n\nAyush'
count
=
0
for
a
in
string:
if
[a.isspace[]]
=
=
True
:
count
+
=
1
print
[count]
Output:
3 8