【发布时间】:2015-10-09 13:51:30
【问题描述】:
我正在尝试编写一个程序来确定一个字符是大写、小写、数字还是非字母数字,而没有像 isupper、islower、isdigit 这样的字符串方法。该程序是我输入的所有内容,它告诉我它是一个小写字母。有人可以帮我吗?
character = input("Enter a character: ")
lowerLetters = "abcdefghijklmnopqrstuvwxyz"
upperLetters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
digits = "0123456789"
lowerCount = 0
upperCount = 0
digitCount = 0
nonAlphaCount = 0
for ch in character:
for ch in lowerLetters:
lowerCount += 1
for ch in upperLetters:
upperCount += 1
for ch in digits:
digitCount += 1
else:
nonAlphaCount += 1
if lowerCount > 0:
print(character, "is a lower case letter.")
elif upperCount > 0:
print(character, "is an upper case letter.")
elif digitCount > 0:
print(character, "is a digit.")
elif nonAlphaCount > 0:
print(character, "is a non-alphanumeric character.")
【问题讨论】:
-
这段代码的问题是你正在这样做:
for ch in lowerLetters: lowerCount += 1。这意味着无论如何,lowerCount 始终为 26。您需要将 lowerLetters 与您的ch进行比较。 -
“字母”的定义各不相同(“数字”也是如此)。即使在英语中,ASCII 字母也不能涵盖整个词汇表。您是否对 ASCII、来自某些语言的字母字符的子集或定义为字母的完整 Unicode 字符集感兴趣?
标签: python python-3.x