Another capitalise every odd char of the string solution

前端 未结 2 1978
花落未央
花落未央 2021-01-14 06:12

I just started studying Python and created some kind of task for myself that I\'m struggling to solve...

So, I\'m on chapter on working with strings (accessing strin

2条回答
  •  离开以前
    2021-01-14 06:45

    You could just use enumerate and test for odd and even indices using a ternary operator. Then use join to join the string:

    >>> T = 'somesampletexthere'
    >>> ''.join(x.upper() if i%2 else x.lower() for i, x in enumerate(T))
    'sOmEsAmPlEtExThErE'
    

    You could handle whitespaces by using an external counter object provided by itertools.count:

    >>> from itertools import count
    >>> c = count()
    >>> T = 'some sample text here'
    >>> ''.join(x if x.isspace() else (x.upper() if next(c)%2 else x.lower()) for x in T)
    'sOmE sAmPlE tExT hErE'
    

提交回复
热议问题