How can I check if a string contains only ASCII letters in Python?
Davide S
In Python, you can check if a string contains only ASCII letters using different approaches. Here's a long-form explanation of a few methods to accomplish this:
1. Using theisascii() Method:
- Python 3.7 introduced thestr.isascii() method, which returnsTrue if all characters in the string are ASCII characters, andFalse otherwise.
- You can directly call theisascii() method on the string you want to check.
- Example:
2. Using Regular Expressions:
- Another approach is to utilize regular expressions to check if a string contains only ASCII letters.
- You can import there module and use there.match() function with a regular expression pattern to match ASCII letters.
- The patternr'^[a-zA-Z]+$' matches a string that consists of one or more ASCII letters (both lowercase and uppercase).
- Example:
3. Using thestring Module:
- Thestring module in Python provides constants for different sets of characters, including ASCII letters.
- Import thestring module and utilize thestring.ascii_letters constant, which contains all ASCII letters (both lowercase and uppercase).
- Iterate over the characters in the string and check if each character belongs to the set of ASCII letters.
- Example:
1
2
3
4
5
import string
string = "Hello"
is_ascii = all(char in string.ascii_letters for char in string)
4. Using theord() Function:
- Theord() function returns the Unicode code point of a character.
- Iterate over the characters in the string and check if the Unicode code point of each character is within the ASCII range (0-127).
- Example:
1
2
3
string = "Hello"
is_ascii = all(0 <= ord(char) <= 127 for char in string)
All of these approaches will returnTrue if the string contains only ASCII letters andFalse otherwise. Choose the method that best suits your requirements and the version of Python you are using.