Swap cases in a string

后端 未结 10 633
天涯浪人
天涯浪人 2021-01-21 15:20

I\'m trying to solve this challenge in hackerrank, which asks to convert all lowercase letters to uppercase letters and vice versa.

I attempt it with the following code:

10条回答
  •  一个人的身影
    2021-01-21 15:31

    As said in comments and othe answers, strings are immutable.

    Try following:

    s = input("Enter input: ")
    
    
    def convert(ss):
        # Convert it into list and then change it
        newSS = list(ss)
        for i,c in enumerate(newSS):
            newSS[i] = c.upper() if c.islower() else c.lower()
        # Convert list back to string
        return ''.join(newSS)
    
    print(s)
    print(convert(s))
    
    # Or use string build in method
    print (s.swapcase())
    

提交回复
热议问题