user2425814
user2425814

Reputation: 409

Efficient way to add spaces between characters in a 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?

Upvotes: 39

Views: 209814

Answers (5)



def space_the_chars(string):
    string = string.upper().replace(' ','')
    return string.replace('','  ')[2:-2]


space_the_chars(“I’m going to be spaced”)  

the function spaces the string’s characters

Upvotes: 0

Guzman Ojero
Guzman Ojero

Reputation: 3457

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'

Upvotes: 3

Mandalorian
Mandalorian

Reputation: 77

The most efficient way is to take input make the logic and run

so the code is like this to make your own space maker

need = input("Write a string:- ")
result = ''
for character in need:
   result = result + character + ' '
print(result)    # to rid of space after O

but if you want to use what python give then use this code

need2 = input("Write a string:- ")

print(" ".join(need2))

Upvotes: 1

John La Rooy
John La Rooy

Reputation: 304147

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

Upvotes: 33

Kevin London
Kevin London

Reputation: 4728

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

Should do it.

Upvotes: 74

Related Questions