how do i insert spaces into a string using the range function?

后端 未结 3 1492
再見小時候
再見小時候 2021-02-15 15:37

If I have a string, for example which reads: \'Hello how are you today Joe\' How am I able to insert spaces into it at regular intervals? So for example I want to insert spaces

3条回答
  •  逝去的感伤
    2021-02-15 16:09

    This does everything!

    >>> def insert_spaces(text, s_range):
            return ' '.join(text[start:end] for start, end in 
                            zip([0] + s_range, s_range + [len(text)])).strip()
    

    The question example:

    >>> insert_spaces('Hello how are you today Joe', range(0, 27, 2))
    'He ll o  ho w  ar e  yo u  to da y  Jo e'
    

    Other examples with different starts, steps and stops:

    >>> insert_spaces('Hello how are you today Joe', range(5, 20, 4))
    'Hello  how  are  you  today Joe'
    >>> insert_spaces('Hello how are you today Joe', range(0, 27))
    'H e l l o   h o w   a r e   y o u   t o d a y   J o e'
    >>> insert_spaces('abcdefghijklmnopqrstuvwxyz', range(0, 16, 5))
    'abcde fghij klmno pqrstuvwxyz'
    

提交回复
热议问题