better way to invert case of string

后端 未结 7 757
迷失自我
迷失自我 2020-12-07 00:43

I am learning python and meet an exercise:

Strings. Create a function that will return another string similar to the input string, but with its case i

相关标签:
7条回答
  • 2020-12-07 01:12

    Your solution is perfectly fine. You don't need three branches though, because str.upper() will return str when upper is not applicable anyway.

    With generator expressions, this can be shortened to:

    >>> name = 'Mr.Ed'
    >>> ''.join(c.lower() if c.isupper() else c.upper() for c in name)
    'mR.eD'
    
    0 讨论(0)
  • 2020-12-07 01:20

    In python, an inbuilt function swapcase() is present which automatically converts the case of each and every letter. Even after entering the mixture of lowercase and uppercase letters it will handle it properly and return the answer as expected.

    Here is my code:

        str1=input("enter str= ")
        res=str1.swapcase()
        print(res)
    
    0 讨论(0)
  • 2020-12-07 01:24

    Simply use the swapcase() method :

    name = "Mr.Ed"
    name = name.swapcase()
    

    Output : mR.eD

    -> This is just a two line code.

    Explanation :
    The method swapcase() returns a copy of the string in which all the case-based characters have had their case swapped.

    Happy Coding!

    0 讨论(0)
  • 2020-12-07 01:24
    #the following program is for toggle case
    name=input()
    for i in name:
        if i.isupper():
            print( i.lower(),sep='',end='')
        else:
            print( i.upper(),sep='',end='')
    
    0 讨论(0)
  • 2020-12-07 01:25
    name='Mr.Ed'
    print(name.swapcase())
    
    0 讨论(0)
  • 2020-12-07 01:31

    https://github.com/suryashekhawat/pythonExamples/blob/master/string_toggle.py

        def toggle(mystr):
            arr = []
            for char in mystr:
                if char.upper() != char:
                    char=char.upper()
                    arr.append(char)
                else:
                    char=char.lower()
                    arr.append(char)
            return ''.join(map(str,arr))
        user_input = raw_input()
        output = toggle(user_input)
        print output
    
    0 讨论(0)
提交回复
热议问题