0

Suppose I have a string as:

s = 'HelloStackOverflow'

What is the most "pythonic" way to convert it to:

'H e l l o S t a c k O v e r f l o w '

?

(space after last character is indifferent)

I could come up with:

s = ''.join(map(lambda ch: ch+' ', s))

But I suppose there is a more transparent way to do it

6
  • 1
    ' '.join(s)-? Commented Dec 13, 2017 at 23:53
  • Do you actually want the trailing space? Commented Dec 13, 2017 at 23:54
  • No, I don't mind abou the trailing space. Either way is fine. (Was my sentence confusing? If so, please edit it to be more clear) Commented Dec 13, 2017 at 23:55
  • 1
    No, but your example very clearly includes a trailing space. Most times it's unwanted, so ' '.join(s) fits the bill if you don't want a trailing space. Commented Dec 14, 2017 at 0:00
  • Simply searching Google for your exact title led me directly to the question I've marked as duplicate. Please do try and do some research before posting questions. Commented Dec 14, 2017 at 1:28

3 Answers 3

2

You can try the following code

' '.join(s)
Out[1]: 'H e l l o S t a c k O v e r f l o w'
Sign up to request clarification or add additional context in comments.

5 Comments

This doesn't meet the OP's requirement of a trailing space.
I am not sure if it is actually needed. I guess we can add a whitespace after it manually with + ' '
cast to list is not needed
Thanks, that seems elegant
@PaulPanzer Agree.
0

Use re.sub and replace each single character in the string by that captured character followed by a single space.

s = 'HelloStackOverflow'
print re.sub("(.)", r'\1 ', s)

H e l l o S t a c k O v e r f l o w 

Demo

4 Comments

Lovely, I'm not sure if it more transparent, but it sure is clever.
My timeit tests show that this is several times slower than ' '.join(s) and functionally equivalent (except for the trailing space which the OP indicated he didn't really want/need), while much more complicated / non-obvious.
@JonathonReinhart Should the OP's replacement requirements change even slightly, the accepted answer would fall short, while a regex based solution would be easily adaptable. I'm not sure this answer merits a downvote.
I could write a C extension to ensure the utmost flexibility for any string manipulation operations the OP may require in the future. Certainly that would not be a good solution, right? Write code for your requirements, not perceived future needs when you aren't gonna need it. More complex, less efficient; I saw this in a code review, I would kick it back immediately.
0
' '.join(s)+' '

For the exact behavior you wanted.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.