Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Efficient way to add spaces between characters in a string

Tags:

python

string

Say I have a string s = 'BINGO'; I want to iterate over the string to produce 'B I N G O'.

This is what I did:

result = '' for ch in s:    result = result + ch + ' ' print(result[:-1])    # to rid of space after O 

Is there a more efficient way to go about this?

like image 594
user2425814 Avatar asked Aug 14 '13 00:08

user2425814


People also ask

How do you put a space between characters in a string?

To add a space between the characters of a string, call the split() method on the string to get an array of characters, and call the join() method on the array to join the substrings with a space separator, e.g. str. split('').

How do you add spaces to a string in Python?

We add space in string in python by using rjust(), ljust(), center() method. To add space between variables in python we can use print() and list the variables separate them by using a comma or by using the format() function.

How do you put a space between characters in C++?

So given: namespace rs = ranges; namespace rv = ranges::views; std::string input = "123"; If you just want to print the string with interspersed spaces, you can do: rs::copy(input | rv::intersperse(' '), rs::ostream_iterator<char>(std::cout));


2 Answers

s = "BINGO" print(" ".join(s)) 

Should do it.

like image 153
Kevin London Avatar answered Oct 10 '22 01:10

Kevin London


s = "BINGO" print(s.replace("", " ")[1: -1]) 

Timings below

$ python -m timeit -s's = "BINGO"' 's.replace(""," ")[1:-1]' 1000000 loops, best of 3: 0.584 usec per loop $ python -m timeit -s's = "BINGO"' '" ".join(s)' 100000 loops, best of 3: 1.54 usec per loop 
like image 24
John La Rooy Avatar answered Oct 10 '22 01:10

John La Rooy