[GO] Python> Implementation> Does it contain numbers | Does it contain alphabet (upper and lower case)> Use sum (), map (), str.isalpha

Operating environment


Python3

Check the following for a specific character string.

-Is there even one number? --Is there even one 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

Is it easier to use regular expressions?

v0.2

I put len () in a lambda expression.

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

--Check upper and lower case letters

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

reference

https://docs.python.org/3/library/stdtypes.html

v0.4

@ SaitoTsutomu's Comment taught me how to use sum (), map (), str.isalpha, etc. ..

Thank you for the 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

Reference> map ()

https://docs.python.jp/3/library/functions.html#map

Recommended Posts

Python> Implementation> Does it contain numbers | Does it contain alphabet (upper and lower case)> Use sum (), map (), str.isalpha
Python> Sort by number and sort by alphabet> Use sorted ()