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

后端 未结 3 2031
没有蜡笔的小新
没有蜡笔的小新 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:49

    Here is a cutesie way to do this:

    >>> s = "This is harder than I thought it would be"
    >>> from itertools import cycle
    >>> funcs = cycle([str.upper, str.lower])
    >>> ''.join(next(funcs)(c) for c in s if c != ' ')
    'ThIsIsHaRdErThAnItHoUgHtItWoUlDbE'
    >>>
    

    Or, as suggested by Moses in the comments, you can use str.isspace, which will take care of not just a single space ' '

    >>> ''.join(next(funcs)(c) for c in s if not c.isspace())
    'ThIsIsHaRdErThAnItHoUgHtItWoUlDbE'
    

    This approach only does a single pass on the string. Although, a two-pass method is likely performant enough.

    Now, if you were starting with a nospace string, the best way is to convert to some mutable type (e.g. a list) and use slice-assignment notation. It's a little bit inefficient because it builds intermediate data structures, but slicing is fast in Python, so it may be quite performant. You have to ''.join at the end, to bring it back to a string:

    >>> nospace
    'ThisisharderthanIthoughtitwouldbe'
    >>> nospace = list(nospace)
    >>> nospace[0::2] = map(str.upper, nospace[0::2])
    >>> nospace[1::2] = map(str.lower, nospace[1::2])
    >>> ''.join(nospace)
    'ThIsIsHaRdErThAnItHoUgHtItWoUlDbE'
    >>>
    

提交回复
热议问题