
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
How to check if a string in Python is in ASCII?
The simplest way is to loop over the characters of the string and check if each character is ASCII or not.
example
def is_ascii(s): return all(ord(c) < 128 for c in s) print is_ascii('ӓmsterdӒm')
Output
This will give the output:
False
But this method is very inefficient. A better way is to decode the string using str.decode('ascii') and check for exceptions.
example
mystring = 'ӓmsterdӓm' try: mystring.decode('ascii') except UnicodeDecodeError: print "Not an ASCII-encoded string" else: print "May be an ASCII-encoded string"
Output
This will give the output:
Not an ASCII-encoded string
- Related Articles
- Is it possible to check if a String only contains ASCII in java?
- How to check if a string is alphanumeric in Python?
- How to check if a string is a valid keyword in Python?
- Check if a string contains only alphabets in Java using ASCII values
- How to check if a character in a string is a letter in Python?
- How to check if type of a variable is string in Python?
- Check if a string is Colindrome in Python
- How to check if a substring is contained in another string in Python
- Check if a string is Pangrammatic Lipogram in Python
- Python - Check if a variable is string
- How to check if a string is empty in Kotlin?
- Check if a string is Isogram or not in Python
- Check if a string is suffix of another in Python
- Check if a given string is a valid number in Python
- How to check if a string only contains certain characters in Python?

Advertisements