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?
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('').
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.
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));
s = "BINGO" print(" ".join(s))
Should do it.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With