How to insert a space before and after a character and put on a new line in Python?

Viewed 138

I need to insert a character before x1 and after x1 and put on a new line

my code:

f='p11p21p31'
y='x1'
k=str(y).join(f[i:i+3] for i in range(0, len(f), 3))
#p=' '.join(k[i:i+3] for i in range(0, len(k), 3))
print(k)

My outout

p11x1p21x1p31

I need:

p11 x1
p21 x1
p31 x1
5 Answers

You were almost there. Using your code:

f='p11p21p31'
y='x1'
k=str(" "+y+"\n").join(f[i:i+3] for i in range(0, len(f), 3))+" "+y
print (k)

Output:

p11 x1
p21 x1
p31 x1

You need to join with a linebreak after your delimiter, and a space preceding that delimiter. You finally add space+delimiter at the end of your string, cause join() on list will not set your delimiter after the last element.

Alternatively:

k= "".join([f[i] if (i+1) % 3 != 0 else f[i]+" "+y+"\n" for i in range(0,len(f))])

In a function:

f='p11p21p31'
y='x1'

def split_fxy(f,x,y):
    return "".join([f[i] if (i+1) % x != 0 else f[i]+" "+y+"\n" for i in range(0,len(f))])

print (split_fxy(f,3,y))

The problem you are facing with join is that it will only add 'x1' between elements you want to join (see the docs). To fix it, you will need to add an extra " x1" at the end.

If you are using Python 3.6+ (which is highly recommended) use the following:

f='p11p21p31'
y='x1'
k= f' {y}\n'.join(f[i:i+3] for i in range(0, len(f), 3)) + f' {y}'
print(k)

If you are using a version prior version to 3.6, use:

f='p11p21p31'
y='x1'
k= ' {}\n'.format(y).join(f[i:i+3] for i in range(0, len(f), 3)) + ' ' + y
print(k)

The previous code will work also even in the case you use Python2 which at this point is strongly discouraged.

Output:

p11 x1
p21 x1
p31 x1

Try join the \n.

f = 'p11p21p31'
y = 'x1'
size = 3  # split each 3 chars

k = '\n'.join(f[i:i+size] + ' ' + y for i in range(0, len(f), 3))
print(k)

You could use a f string to make you intent more clear:

f='p11p21p31'
y='x1'
print(''.join([f'{f[i:i+3]} {y}\n' for i in range(0,len(f),3) ]))

Prints:

p11 x1
p21 x1
p31 x1

With a regex based solution

1/ split according to your pattern

2/ filter null item

3/ concat x1 to all item

4/ join with \n

import re

f='p11p21p31'
#      4                3                         2          1
print("\n".join(map(lambda i: i+" x1", list(filter(None, re.split(r'([a-z]*[0-9]+)', f))))))
Related