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

后端 未结 3 1493
再見小時候
再見小時候 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'
    
    0 讨论(0)
  • 2021-02-15 16:23

    Just another way to do it

    >>> ''.join(e if (i+1)%2 else e+" " for (i,e) in enumerate(list(s)))
    'He ll o  ho w  ar e  yo u  to da y  Jo e'
    
    0 讨论(0)
  • 2021-02-15 16:24

    The most straight-forward approach for this particular case is

    s = 'Hello how are you today Joe'
    s = " ".join(s[i:i+2] for i in range(0, len(s), 2))
    

    This splits the string into chunks of two characters each first, and then joins these chunks with spaces.

    0 讨论(0)
提交回复
热议问题