2
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Python > 実装 > 数値が入っているか | alphabet(upper and lower case)が入っているか > sum(), map(), str.isalphaの使用

Last updated at Posted at 2017-07-27
動作環境
Python3

特定の文字列に以下の確認をする。

  • 数値が1つでも入っているか
  • alphabetが1つでも入っているか

v0.1

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

正規表現使う方が楽だろうか。

v0.2

len()を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

  • Upper, lower case letterのチェック

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

参考

v0.4

@SaitoTsutomu さんのコメントにてsum(), map(), str.isalphaなどの使用方法を教えていただきました。

情報感謝です。

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

参考 > map()

2
6
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?