How can I check if character in a string is a letter? (Python)
You can use str.isalpha()
.
For example:
s = 'a123b'
for char in s:
print(char, char.isalpha())
Output:
a True
1 False
2 False
3 False
b True
How to check a string for specific characters?
Assuming your string is s
:
'$' in s # found
'$' not in s # not found
# original answer given, but less Pythonic than the above...
s.find('$')==-1 # not found
s.find('$')!=-1 # found
And so on for other characters.
... or
pattern = re.compile(r'\d\$,')
if pattern.findall(s):
print('Found')
else
print('Not found')
... or
chars = set('0123456789$,')
if any((c in chars) for c in s):
print('Found')
else:
print('Not Found')
[Edit: added the '$' in s
answers]
How would I check a string for a certain letter in Python?
Use the in
keyword without is
.
if "x" in dog:
print "Yes!"
If you'd like to check for the non-existence of a character, use not in
:
if "x" not in dog:
print "No!"
Detect whether a Python string is a number or a letter
Check if string is nonnegative digit (integer) and alphabet
You may use str.isdigit()
and str.isalpha()
to check whether a given string is a nonnegative integer (0 or greater) and alphabetical character, respectively.
Sample Results:
# For alphabet
>>> 'A'.isdigit()
False
>>> 'A'.isalpha()
True
# For digit
>>> '1'.isdigit()
True
>>> '1'.isalpha()
False
Check for strings as positive/negative - integer/float
str.isdigit()
returns False
if the string is a negative number or a float number. For example:
# returns `False` for float
>>> '123.3'.isdigit()
False
# returns `False` for negative number
>>> '-123'.isdigit()
False
If you want to also check for the negative integers and float
, then you may write a custom function to check for it as:
def is_number(n):
try:
float(n) # Type-casting the string to `float`.
# If string is not a valid `float`,
# it'll raise `ValueError` exception
except ValueError:
return False
return True
Sample Run:
>>> is_number('123') # positive integer number
True
>>> is_number('123.4') # positive float number
True
>>> is_number('-123') # negative integer number
True
>>> is_number('-123.4') # negative `float` number
True
>>> is_number('abc') # `False` for "some random" string
False
Discard "NaN" (not a number) strings while checking for number
The above functions will return True
for the "NAN" (Not a number) string because for Python it is valid float representing it is not a number. For example:
>>> is_number('NaN')
True
In order to check whether the number is "NaN", you may use math.isnan()
as:
>>> import math
>>> nan_num = float('nan')
>>> math.isnan(nan_num)
True
Or if you don't want to import additional library to check this, then you may simply check it via comparing it with itself using ==
. Python returns False
when nan
float is compared with itself. For example:
# `nan_num` variable is taken from above example
>>> nan_num == nan_num
False
Hence, above function is_number
can be updated to return False
for "NaN"
as:
def is_number(n):
is_number = True
try:
num = float(n)
# check for "nan" floats
is_number = num == num # or use `math.isnan(num)`
except ValueError:
is_number = False
return is_number
Sample Run:
>>> is_number('Nan') # not a number "Nan" string
False
>>> is_number('nan') # not a number string "nan" with all lower cased
False
>>> is_number('123') # positive integer
True
>>> is_number('-123') # negative integer
True
>>> is_number('-1.12') # negative `float`
True
>>> is_number('abc') # "some random" string
False
Allow Complex Number like "1+2j" to be treated as valid number
The above function will still return you False
for the complex numbers. If you want your is_number
function to treat complex numbers as valid number, then you need to type cast your passed string to complex()
instead of float()
. Then your is_number
function will look like:
def is_number(n):
is_number = True
try:
# v type-casting the number here as `complex`, instead of `float`
num = complex(n)
is_number = num == num
except ValueError:
is_number = False
return is_number
Sample Run:
>>> is_number('1+2j') # Valid
True # : complex number
>>> is_number('1+ 2j') # Invalid
False # : string with space in complex number represetantion
# is treated as invalid complex number
>>> is_number('123') # Valid
True # : positive integer
>>> is_number('-123') # Valid
True # : negative integer
>>> is_number('abc') # Invalid
False # : some random string, not a valid number
>>> is_number('nan') # Invalid
False # : not a number "nan" string
PS: Each operation for each check depending on the type of number comes with additional overhead. Choose the version of is_number
function which fits your requirement.
How can I check if a string contains ANY letters from the alphabet?
Regex should be a fast approach:
re.search('[a-zA-Z]', the_string)
Check if one character in string is numeric or is a letter [Python]
You could use re.search
if re.search(r'[a-zA-Z\d]', string):
It will return a match object if the string contain at-least a letter or a digit.
Example:
>>> s = "foo0?"
>>> re.search(r'[a-zA-Z\d]', s)
<_sre.SRE_Match object; span=(0, 1), match='f'>
>>> s = "???"
>>> re.search(r'[a-zA-Z\d]', s)
>>> s = "???0"
>>> re.search(r'[a-zA-Z\d]', s)
<_sre.SRE_Match object; span=(3, 4), match='0'>
>>>
How to check that a string contains only “a-z”, “A-Z” and “0-9” characters
You could use regex for this, e.g. check string against following pattern:
import re
pattern = re.compile("[A-Za-z0-9]+")
pattern.fullmatch(string)
Explanation:
[A-Za-z0-9]
matches a character in the range of A-Z, a-z and 0-9, so letters and numbers.
+
means to match 1 or more of the preceeding token.
The re.fullmatch()
method allows to check if the whole string matches the regular expression pattern. Returns a corresponding match object if match found, else returns None
if the string does not match the pattern.
All together:
import re
if __name__ == '__main__':
string = "YourString123"
pattern = re.compile("[A-Za-z0-9]+")
# if found match (entire string matches pattern)
if pattern.fullmatch(string) is not None:
print("Found match: " + string)
else:
# if not found match
print("No match")
Related Topics
Set Markers for Individual Points on a Line in Matplotlib
Python: Call a Function from String Name
Check List of Words in Another String
Retrieving a Foreign Key Value with Django-Rest-Framework Serializers
Duplicate Log Output When Using Python Logging Module
The Problem with Installing Pil Using Virtualenv or Buildout
Typeerror: Unsupported Operand Type(S) for /: 'Str' and 'Str'
How to Uninstall a Package Installed with Pip Install --User
How to Get Item's Position in a List
Python List Directory, Subdirectory, and Files
How to Extract Top-Level Domain Name (Tld) from Url
Downloading with Chrome Headless and Selenium
How to Group a List of Tuples/Objects by Similar Index/Attribute in Python