

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 Questions & Answers
- Is it possible to check if a String only contains ASCII in java?
- How to check if a string is alphanumeric in Python?
- Check if a string is Colindrome in Python
- Python - Check if a variable is string
- How to check if a string is a valid keyword in Python?
- Check if a string contains only alphabets in Java using ASCII values
- Check if a string is Pangrammatic Lipogram in Python
- How to check if type of a variable is string in Python?
- How to check if a character in a string is a letter in Python?
- How to check if a substring is contained in another string in Python
- 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 String is empty in Java?
Advertisements