Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
276 views
in Technique[技术] by (71.8m points)

python - List all the upper and lowercase letters in a string

I want to list all the upper and lowercase letters in a string,but the code below in python isn't working:

def up_low(s):
    for letter in s :
        v = []
        v1 = []
        if letter.islower() :
            v = v.append(1)
        elif letter.isupper():
            v1=v1.append(1)
        else :
            pass
        return len(v)
        return len(v1)

print(up_low("Hello Siam,'How are You Today?'"))
question from:https://stackoverflow.com/questions/65840145/list-all-the-upper-and-lowercase-letters-in-a-string

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Your current code fails because you keep resetting v and v1 to an empty list every time you pick a new letter. You can do this more directly with list comprehensions:

v  = [char for char in s if char.islower()]
v1 = [char for char in s if char.isupper()]

However, since what you really want is the count, simply add the Boolean values (which are True = 1 and False = 0)

len_lower = sum(char.islower() for char in s)
len_upper = sum(char.isupper() for char in s)

... and there are your two values to return


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...