How can I check if a string contains only alphabetic characters and spaces in Python?
Davide S
To check if a string contains only alphabetic characters and spaces in Python, you can utilize regular expressions and there module. Regular expressions provide powerful pattern matching capabilities to identify specific character sequences in strings.
Here's an example of how you can perform this check:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
import re
def contains_only_alpha_and_space(string):
pattern = r'^[A-Za-z\s]+$'
match = re.match(pattern, string)
return match is not None
# Usage:
input_string = input("Enter a string: ")
if contains_only_alpha_and_space(input_string):
print("The string contains only alphabetic characters and spaces.")
else:
print("The string contains non-alphabetic or non-space characters.")
In the above code, thecontains_only_alpha_and_space() function takes astring parameter. It defines a regular expression patternr'^[A-Za-z\s]+$' to match the string.
The pattern breakdown:
-^ asserts the start of the string.
-[A-Za-z] matches any uppercase or lowercase alphabetic character.
-\s matches any whitespace character (including spaces).
-+ allows one or more occurrences of the preceding pattern.
-$ asserts the end of the string.
There.match() function attempts to match the pattern against the string. If a match is found, it returns a match object; otherwise, it returnsNone.
By checking if the match object is notNone, we can determine if the string contains only alphabetic characters and spaces. If the match object isNone, it means that the string contains non-alphabetic or non-space characters.
You can use thecontains_only_alpha_and_space() function by providing a string as an argument. It will check if the string contains only alphabetic characters and spaces based on the regular expression pattern. The result is then printed accordingly.
Please note that the regular expression pattern used in this example considers only ASCII alphabetic characters. If you need to include non-ASCII characters, you can modify the pattern to accommodate your specific requirements.