如何在没有字符串方法的情况下确定字符是大写,小写,数字还是非字母数字

时间:2015-10-09 13:51:31

标签: python python-3.x

我正在尝试编写一个程序,用于确定字符是大写,小写,数字还是非字母数字,而不使用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.")

2 个答案:

答案 0 :(得分:4)

您可以使用ascii值

Numbers 0-9 ASCII 48 to 57 
Lowercase letters a-z ASCII 97 to 122 
Uppercase letters A-Z ASCII 65-90

使用ord功能。像这样:

>>ord('a')
97 

因此,要检查a是否为小写字母,请执行以下操作:

if 97<=ord('a')<=122:
    print "lowercase character"

答案 1 :(得分:3)

你的代码很好(虽然不是最适合你的目的,即使你没有使用你提到的方法)但是你有一些错别字:)这就是你所拥有的:

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

这就是你想要输入:

for ch in character:
    if ch in lowerLetters:
        lowerCount += 1
    elif ch in upperLetters:
        upperCount += 1
    elif ch in digits:
        digitCount += 1
    else:
        nonAlphaCount += 1