Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

python - Swapping uppercase and lowercase in a string

I would like to change the chars of a string from lowercase to uppercase.

My code is below, the output I get with my code is a; could you please tell me where I am wrong and explain why? Thanks in advance

test = "AltERNating"

def to_alternating_case(string):
    words = list(string)
    for word in words:
        if word.isupper() == True:
            return word.lower()
        else:
            return word.upper()  

print to_alternating_case(test)
See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

If you want to invert the case of that string, try this:

>>> 'AltERNating'.swapcase()
'aLTernATING'

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...