Swap cases in a string

后端 未结 10 621
天涯浪人
天涯浪人 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:26
    def swap_case(s):
        new = ""
        for i in range(len(s)):
            if str.isupper(s[i]):
                new = new + str.lower(s[i])
    
            elif str.islower(s[i]):
                new = new + str.upper(s[i])
    
            else:
                new = new + str(s[i])
            
        return (new)
    
    if __name__ == '__main__':
        s = input()
        result = swap_case(s)
        print(result)
    
    0 讨论(0)
  • 2021-01-21 15:26
    def swap_case(s):
        l = list(s)
        for i in range(len(s)):
            if l[i].islower():
                l[i] = l[i].upper()
            else:
                l[i] = l[i].lower()
        k = "".join(map(str,l))
        return k
    
    0 讨论(0)
  • 2021-01-21 15:30

    Python-3 in-built swapcase function.

    def swap_case(s):
        return s.swapcase()
    
    if __name__ == '__main__':
        s = input()
        result = swap_case(s)
        print(result)
    

    Input:

    "Pythonist 3"
    

    Output:

    "pYTHONIST 3"
    
    0 讨论(0)
  • 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())
    
    0 讨论(0)
  • 2021-01-21 15:31
    def swap_case(s):
        a=" "
        for i in s:
            if i==i.lower():
                a=a+(i.upper())
            else:
                a=a+(i.lower())
        return (a)
    
    0 讨论(0)
  • 2021-01-21 15:33

    The built-in str.swapcase already does this.

    def swap_case(s):
        return s.swapcase()
    
    0 讨论(0)
提交回复
热议问题