Pythonは、文字列内の数字、英字、スペース、その他の文字の数をカウントします

数字、英字、スペース、その他の文字は、ASCIIコードテーブルで1対1で対応しています。ord関数を使用して、この問題を解決できます。

ord()関数は、chr()関数(8ビットASCII文字列の場合)またはunichr()関数(Unicodeオブジェクトの場合)の対関数です。パラメーターとして文字(長さ1の文字列)を取り、を返します。対応するASCII値またはUnicode値。指定されたUnicode文字がPython定義の範囲を超えると、TypeError例外が発生します。


まず、ここでASCIIコードを使用することを考えます。ASCIIコード変換表は次のとおりです。


0〜9桁のASCIIコード値の範囲は48〜57です。

a〜z小文字の英字の値の範囲は97〜122です

A〜Zの大文字の英字の値の範囲は65〜90です。

sstr=list(input("Please enter a string: "))

alphas=[]
digits=[]
spaces=[]
others=[]

for i in range(len(sstr)):
	if ord(sstr[i]) in range(48,58):
		digits.append(sstr[i])
	elif ord(sstr[i]) in range(65,91) or ord(sstr[i]) in range(97,123):
		alphas.append(sstr[i])
	elif ord(sstr[i])==32:
		spaces.append(sstr[i])
	else:
		others.append(sstr[i])
print("The number of alpha is "+str(len(alphas))+".\n"
      +"The number of digit is "+str(len(digits))+".\n"
      +"The number of space is "+str(len(spaces))+".\n"
      +"The number of others is "+str(len(others))+".")


おすすめ

転載: blog.csdn.net/wxy_csdn_world/article/details/80741280