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
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'
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'
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.