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'

Community
  • 1
  • 1
Leo
  • 649
  • 3
  • 9
  • 20
  • 3
    So you want to add a space after every second character? What have you tried so far? – poke Nov 09 '12 at 19:11

4 Answers4

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'
Xavier
  • 1,536
  • 2
  • 16
  • 29
Paolo Moretti
  • 54,162
  • 23
  • 101
  • 92
0
def isection(itr, size):
    while itr:
        yield itr[:size]
        itr = itr[size:]

' '.join(isection('akhfkahgdsds', 2))
pydsigner
  • 2,779
  • 1
  • 20
  • 33
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*' ')
mgilson
  • 300,191
  • 65
  • 633
  • 696
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
jkalivas
  • 1,117
  • 1
  • 8
  • 11