How can I check if a string contains only whitespace characters in Python without using regular expressions?
Davide S
To check if a string contains only whitespace characters in Python without using regular expressions, you can use theisspace() method and a loop to iterate through each character in the string. Theisspace() method returnsTrue if a character is a whitespace character andFalse otherwise.
Here's an example of how you can perform this check:
1
2
3
4
5
6
7
8
9
10
11
12
13
def contains_only_whitespace(string):
for char in string:
if not char.isspace():
return False
return True
# Usage:
input_string = input("Enter a string: ")
if contains_only_whitespace(input_string):
print("The string contains only whitespace characters.")
else:
print("The string contains non-whitespace characters.")
In the above code, thecontains_only_whitespace() function takes astring parameter representing the input string to check. It iterates through each character in the string using afor loop and checks if the character is a whitespace character using theisspace() method.
If any non-whitespace character is encountered, the function immediately returnsFalse, indicating that the string contains non-whitespace characters. If the loop completes without finding any non-whitespace characters, the function returnsTrue, indicating that the string contains only whitespace characters.
You can use thecontains_only_whitespace() function by providing a string as an argument. It will check if the string contains only whitespace characters using theisspace() method and the loop. The result is then printed accordingly.
This approach allows you to check if a string contains only whitespace characters without using regular expressions. It provides a straightforward and efficient solution by iterating through each character and checking its whitespace status.