Efficient way to add spaces between characters in a string
Solution 1:
s = "BINGO"
print(" ".join(s))
Should do it.
Solution 2:
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
Solution 3:
The Pythonic way
A very pythonic and practical way to do it is by using the string join()
method:
str.join(iterable)
The official Python documentations says:
Return a string which is the concatenation of the strings in iterable... The separator between elements is the string providing this method.
How to use it?
Remember: this is a string method.
This method will be applied to the str
above, which reflects the string that will be used as separator of the items in the iterable.
Let's have some practical example!
iterable = "BINGO"
separator = " " # A whitespace character.
# The string to which the method will be applied
separator.join(iterable)
> 'B I N G O'
In practice you would do it like this:
iterable = "BINGO"
" ".join(iterable)
> 'B I N G O'
But remember that the argument is an iterable, like a string, list, tuple. Although the method returns a string.
iterable = ['B', 'I', 'N', 'G', 'O']
" ".join(iterable)
> 'B I N G O'
What happens if you use a hyphen as a string instead?
iterable = ['B', 'I', 'N', 'G', 'O']
"-".join(iterable)
> 'B-I-N-G-O'