Python String isspace() method
Python String isspace() method
The string.isspace() method returns a Boolean value true if there are only whitespace characters in the given string. This function is used to check if the given string contains any whitespace characters. The common example of whitespace characters are as follows:
- ‘ ‘ – Space
- ‘\t’ – Horizontal tab
- ‘\n’ – Newline
- ‘\v’ – Vertical tab
- ‘\f’ – Feed
- ‘\r’ – Carriage return
Syntax
String.isspace()
Parameter
NA
Return
This method returns a boolean value “True” if all characters in the string are whitespace characters, else it returns “False” if the string contains 1 or more non-whitespace characters.
Example 1
# Python program explaining # the isspace() method strVal = " \t" print("String 1=",strVal) print("The isspace() method returns: ",strVal.isspace()) strVal = " a " print("String 2=",strVal) print("The isspace() method returns: ",strVal.isspace()) strVal = "" print("String 3=",strVal) print("The isspace() method returns: ",strVal.isspace())
Output
String 1= The isspace() method returns: True String 2= a The isspace() method returns: False String 3= The isspace() method returns: False
Example 2
# Python program explaining # the isspace() method # initializing a string value string = "Tutorials and Examples" print(string.isspace()) # checking if \n is a whitespace character string = "\t \t \t" print(string.isspace()) # if the string contains 1 or more non-whitespace characters # this method returns false string = "Tutorials\nand\nExamples" print( string.isspace())
Output
False True False
Example 3
# Python program explaining # the isspace() method # initializing a string value string = '\t \n' print("String 1:",string) if string.isspace() == True: print('All the characters in the string are whitespace characters') else: print('The string contain 1 or more non-whitespace characters') # initializing a second string string = '7*2 = 14' print("String 2:",string) if string.isspace() == True: print('All the characters in the string are whitespace characters') else: print('The string contain 1 or more non-whitespace characters')
Output
String 1: All the characters in the string are whitespace characters String 2: 7*2 = 14 The string contain 1 or more non-whitespace characters