Environnement d'exploitation
Python3
Vérifiez les éléments suivants pour une chaîne de caractères spécifique.
-Est-il même un numéro? -Y a-t-il même un alphabet?
v0.1
http://ideone.com/H6gVVV
checkalpha = lambda t:[e for e in t if e.isalpha()]
checkdigit = lambda t:[e for e in t if e.isdigit()]
atxt = '1234b'
print(checkalpha(atxt))
print(checkdigit(atxt))
btxt = '12345'
print(checkalpha(btxt))
print(checkdigit(btxt))
if len(checkalpha(btxt)) == 0:
print("no alphabet")
run
['b']
['1', '2', '3', '4']
[]
['1', '2', '3', '4', '5']
no alphabet
Est-il plus facile d'utiliser des expressions régulières?
v0.2
J'ai mis len () dans une expression lambda.
numalpha = lambda t:len([e for e in t if e.isalpha()])
numdigit = lambda t:len([e for e in t if e.isdigit()])
atxt = '1234b'
print(numalpha(atxt))
print(numdigit(atxt))
btxt = '12345'
print(numalpha(btxt))
print(numdigit(btxt))
if numalpha(btxt) == 0:
print("no alphabet")
run
1
4
0
5
no alphabet
v0.3
http://ideone.com/C74yMc
numlower = lambda t:len([e for e in t if e.islower()])
numupper = lambda t:len([e for e in t if e.isupper()])
numdigit = lambda t:len([e for e in t if e.isdigit()])
def checkfunc(txt):
print("===%s===" % txt)
print("lower:%d, upper:%d, digit:%d" %
(numlower(txt), numupper(txt), numdigit(txt)))
if numlower(txt) == 0:
print("no lower case letters")
if numupper(txt) == 0:
print("no upper case letters")
if numdigit(txt) == 0:
print("no digits")
atxt = '1234b'
checkfunc(atxt)
btxt = '12345'
checkfunc(btxt)
run
===1234b===
lower:1, upper:0, digit:4
no upper case letters
===12345===
lower:0, upper:0, digit:5
no lower case letters
no upper case letters
https://docs.python.org/3/library/stdtypes.html
v0.4
Le [Comment] de @ SaitoTsutomu (http://qiita.com/7of9/items/b5a307fed35f333f1d29/#comment-08652be67cebfb281ecf) m'a appris à utiliser sum (), map (), str.isalpha, etc. ..
Merci pour l'information.
http://ideone.com/oTCBE4
numlower = lambda s:sum(map(str.islower, s))
numupper = lambda s:sum(map(str.isupper, s))
numdigit = lambda s:sum(map(str.isdigit, s))
def checkfunc(txt):
print("===%s===" % txt)
print("lower:%d, upper:%d, digit:%d" %
(numlower(txt), numupper(txt), numdigit(txt)))
if numlower(txt) == 0:
print("no lower case letters")
if numupper(txt) == 0:
print("no upper case letters")
if numdigit(txt) == 0:
print("no digits")
atxt = '1234b'
checkfunc(atxt)
btxt = '12345'
checkfunc(btxt)
run
===1234b===
lower:1, upper:0, digit:4
no upper case letters
===12345===
lower:0, upper:0, digit:5
no lower case letters
no upper case letters
https://docs.python.jp/3/library/functions.html#map