Swap cases in a string

后端 未结 10 615
天涯浪人
天涯浪人 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:38

    Try this

    def swap_case(s):
        l =[]
        str1 = ''
        for i in s:
            if i.isupper():
    
                l.append(i.lower())
            elif i.islower():
                l.append(i.upper())
            else:
                l.append(i)
        return (str1.join(l))
    if __name__ == '__main__':
        s = input()
        result = swap_case(s)
        print(result)
    
    0 讨论(0)
  • 2021-01-21 15:47

    As @Julien stated in comment upper and lower methods return a copy, and do not change the object itself. See this docs.

    EDIT @aryamccarthy reminded me of already existing feature for this kind of task in python: swapcase() method. See more here. Note this also returns a copy of the string.

    0 讨论(0)
  • 2021-01-21 15:47
    def swap_case(s):
        return s.swapcase()
    
    #or you can use list comprehension 
    
    def swap_case(s):
        new=[ch.lower() if ch.isupper() else ch.upper() for ch in s]
        new=''.join(new)
        return new
    
    if __name__ == '__main__':
        s = input()
        result = swap_case(s)
        print(result)
    
    0 讨论(0)
  • 2021-01-21 15:49
    def swap_case(s):
        list_s= list(s)
        for index,char in enumerate(list_s):
            if char == char.lower():
                list_s[index] =char.upper()
            else:
                list_s[index]= char.lower()
                s = ''.join(list_s)
        return s
    
    string = 'HackerRank.com presents "Pythonist 2".'
    print(swap_case(string))
    
    0 讨论(0)
提交回复
热议问题