How can I check if a string contains only alphanumeric characters and spaces in Python?
Alex K
To check if a string contains only alphanumeric characters and spaces in Python, you can use a combination of string methods and theisspace() method. Theisalnum() method checks if a character is alphanumeric, and theisspace() method checks if a character is a space character.
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_alnum_and_space(string):
for char in string:
if not (char.isalnum() or char.isspace()):
return False
return True
# Usage:
input_string = input("Enter a string: ")
if contains_only_alnum_and_space(input_string):
print("The string contains only alphanumeric characters and spaces.")
else:
print("The string contains non-alphanumeric characters or non-space characters.")
In the above code, thecontains_only_alnum_and_space() function takes astring parameter representing the input string to check. It iterates through each character in the string using afor loop.
Inside the loop, it uses theisalnum() method to check if the character is alphanumeric (a letter or a digit) and theisspace() method to check if the character is a space character. Theisalnum() method returnsTrue if the character is alphanumeric, and theisspace() method returnsTrue if the character is a space character.
If any character is found that is neither alphanumeric nor a space character, the function immediately returnsFalse, indicating that the string contains non-alphanumeric or non-space characters. If the loop completes without finding any non-alphanumeric or non-space characters, the function returnsTrue, indicating that the string contains only alphanumeric characters and spaces.
You can use thecontains_only_alnum_and_space() function by providing a string as an argument. It will check if the string contains only alphanumeric characters and spaces by using theisalnum() andisspace() methods in the loop. The result is then printed accordingly.
This approach provides a straightforward solution to check if a string contains only alphanumeric characters and spaces. It allows you to handle various types of input strings and determine if they meet the specified criteria.