+ 6
In python ; how can i test if a character exist or not in a list that begin from 0 to 9 ... or from list a to z ?
8 ответов
+ 6
Diego thank you
+ 6
Seb TheS thank you
+ 5
print("a" in "0123456789")
# False
print("a" in "abcdefghijklmnopqrstuvwxyz")
# True
+ 5
Abdelkader Barraj
print("a"in [chr(i) for i in range(48,58)])
# False
print("a" [chr(i) for i in range(97,123)])
# True
+ 5
Diego
It's a test not a loop ..
I whould like to test if a caracter is a letter or a number
+ 3
You can use regular expression (re), but for just a character, there is another solution:
This is how to check whether a character is digit, uppercase or lowercase letter:
function ord, returns an unique position of a character in a list of 2^16 (=65536) different characters.
"0": 48, "9": 57
"A": 65, "Z": 90
"a": 97, "z": 122
You can test whether character is:
A digit:
48 <= ord("7") <= 57 #True
48 <= ord("0") <= 57 #True
48 <= ord("A") <= 57 #False
An uppercase character:
65 <= ord("F") <= 90 #True
65 <= ord("f") <= 90 #False
65 <= ord("9") <= 90 #False
A lowercase letter:
97 <= ord("e") <= 90 #True
97 <= ord("z") <= 90 #True
97 <= ord("O") <= 90 #False
+ 2
Then you can use this information to check whether all, or atleast one of the characters in a list or a string is digit, lowercase letter or uppercase letter using any and all functions, and list comprehension.
#All characters in "An abstract 123 class" must be digits.
text = "An abstract 123 class"
all(48 <= c <= 57 for c in text) #False
#Atleast one character in "Abstract 123 class" must be an uppercase letter:
any(65 <= c <= 90 for c in text) #True