How do I insert spaces in a string using a range function?

If I have a line, for example, that reads: "Hello, how are you today, Joe." How can I insert spaces into it at regular intervals? So, for example, I want to insert spaces into it, using the range function in the following steps: range (0.27.2). So it will look like this:

"He ll o ho w ar e yo u to da y Jo e" 

Now it has space at every second index approaching it. How do I do this, does anyone know? thanks.

+7
source share
3 answers

The most direct approach for this case is

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

This first breaks the string into pieces of two characters, and then concatenates these pieces with spaces.

+12
source

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' 
+1
source

It 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() 

Example question:

 >>> 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 ellohowareyoutoday J oe' >>> insert_spaces('abcdefghijklmnopqrstuvwxyz', range(0, 16, 5)) 'abcde fghij klmno pqrstuvwxyz' 
0
source

All Articles