简体   繁体   English

Python中如何在字符前后插入空格并换行?

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

I need to insert a character before x1 and after x1 and put on a new line我需要在 x1 之前和 x1 之后插入一个字符并换行

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

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: 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.您最后在字符串的末尾添加了空格+分隔符,因为 list 上的join()不会在最后一个元素之后设置分隔符。

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:在 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 ).您在加入时面临的问题是它只会在您要加入的元素之间添加'x1'请参阅文档)。 To fix it, you will need to add an extra " x1" at the end.要修复它,您需要在末尾添加一个额外的" x1"

If you are using Python 3.6+ (which is highly recommended) use the following:如果您使用的是 Python 3.6+(强烈推荐),请使用以下内容:

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:如果您使用的是 3.6 之前的版本,请使用:

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.即使在您使用 Python2 的情况下,前面的代码也可以工作,此时强烈建议不要这样做。

Output: Output:

p11 x1
p21 x1
p31 x1

Try join the \n .尝试join \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字符串使您的意图更清晰:

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 1/根据你的模式拆分

2/ filter null item 2/ 过滤器 null 项目

3/ concat x1 to all item 3/ 将 x1 连接到所有项目

4/ join with \n 4/ 加入\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))))))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM