Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

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 into it using the range function in these 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"

It now has a space at every 2nd index going up to it's end. How do I do this does anyone know? thanks.

like image 405
user1319219 Avatar asked Apr 07 '12 15:04

user1319219


1 Answers

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.

like image 89
Sven Marnach Avatar answered Nov 06 '22 06:11

Sven Marnach