0

Possible Duplicate:
Pythonic way to insert every 2 elements in a string

I'll be happy if someone can help with python code)) How can I put the space into a string for example,

If there is the string 'akhfkahgdsds' I would like to turn it into 'ak hf ka hg ds ds'

1
  • 3
    So you want to add a space after every second character? What have you tried so far? Commented Nov 9, 2012 at 19:11

4 Answers 4

7
>>> s = 'akhfkahgdsds'
>>> range(0, len(s), 2) # gives you the start indexes of your substrings
[0, 2, 4, 6, 8, 10]
>>> [s[i:i+2] for i in range(0, len(s), 2)] # gives you the substrings
['ak', 'hf', 'ka', 'hg', 'ds', 'ds']
>>> ' '.join(s[i:i+2] for i in range(0, len(s), 2)) # join the substrings with spaces between them
'ak hf ka hg ds ds'
Sign up to request clarification or add additional context in comments.

2 Comments

actually, this command doesn't work, I'm using python 2.7.3
@user1813163 I've tested it on Python 2.7 and 3.3. Are you sure you pasted it correctly? What error are you getting?
0
def isection(itr, size):
    while itr:
        yield itr[:size]
        itr = itr[size:]

' '.join(isection('akhfkahgdsds', 2))

Comments

0

I don't really think this is the way to go here, but I think this answer is kind of fun anyway. If the length of the string is always even, you can play neat tricks with iter -- if it's odd, the last character will be truncated:

s = '11223344'
i_s = iter(s)
' '.join(x+next(i_s) for x in i_s)

Of course, you can always pad it:

i_s = iter(s+len(s)%2*' ')

Comments

0

you can try this simple code:

try:
    for i in range(0,len(s)+1,2):
        print s[i]+s[i+1],
except IndexError:
    pass

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.