Another alternating-case in-a-string in Python 3.+

后端 未结 3 2088
没有蜡笔的小新
没有蜡笔的小新 2021-01-24 18:17

I\'m very new to Python and am trying to understand how to manipulate strings.

What I want to do is change a string by removing the spaces and alternating the case from

3条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-24 18:37

    So your 2nd loop is where you're breaking it, because the original list isn't being shortened, the c=nospace[:1] grabs the first character of the string and that's the only character that's ever printed. So a solution would be as follows.

    string1 = str(input("Ask user for something."))
    
    nospace = ''.join(string1.split(' '))
    
    for i in range(0, len(nospace)):
        if i % 2 == 0:
            print(nospace[i].upper(), end="")
        else:
            print(nospace[i].lower(), end="")
    

    Could also replace the if/else statement with a ternary opperator.

    for i in range(0, len(nospace)):
        print(nospace[i].upper() if (i % 2 == 0) else nospace[i].lower(), end='')
    

    Final way using enumerate as commented about

    for i, c in enumerate(nospace):
        print(c.upper() if (i % 2 == 0) else c.lower(), end='')
    

提交回复
热议问题