简体   繁体   English

如何在 python 中的特定字符编号的字符串中添加新行?

[英]How to add new line in a string at a particular character number in python?

Input Received:输入收到:

Line: agrgb This is a good planet
Line: 4f1g6 I like toast
Line: ew5je I like horseriding

How can I add a new line before each comment in the output.如何在 output 中的每条评论前添加一个新行。

Line: agrgb
This is a good plant
Line: 4f1g6
I like toast
Line: ew5je
I like horseriding

You could do it like this:你可以这样做:

Input = ['Line: agrgb This is a good planet', 'Line: 4f1g6 I like toast', 'Line: ew5je I like horseriding']
for i in Input:
    split = i.split()
    print(' '.join(i for i in split[:2]))
    print(' '.join(i for i in split[2:]))

Output: Output:

Line: agrgb
This is a good planet
Line: 4f1g6
I like toast
Line: ew5je
I like horseriding

And if Input is a single string you can convert it to the list shown above like this:如果Input是单个字符串,您可以将其转换为上面显示的列表,如下所示:

Input = 'Line: agrgb This is a good planet Line: 4f1g6 I like toast Line: ew5je I like horseriding'
Input = [f'Line:{i}' for i in Input.split('Line:') if i]

You can try re.sub你可以试试re.sub

import re

data = """
Line: agrgb This is a good planet
Line: 4f1g6 I like toast
Line: ew5je I like horseriding
"""

out = re.sub(r'(Line: [^ ]*) (.*)', r'\1\n\2', data)
print(out)

Line: agrgb
This is a good planet
Line: 4f1g6
I like toast
Line: ew5je
I like horseriding

Here is one approach:这是一种方法:

text = """Line: agrgb This is a good planet
Line: 4f1g6 I like toast
Line: ew5je I like horseriding"""

result = []
for line in text.splitlines():
    line_header, that_number, comment = line.split(maxsplit=2)
    result.append(f"{line_header} {that_number}\n{comment}")

print("\n".join(result))

output: output:

Line: agrgb
This is a good planet
Line: 4f1g6
I like toast
Line: ew5je
I like horseriding

I splited each line with maxsplit=2 to get those three parts that I'm interested in. Then I built my new line using f-string.我用maxsplit=2拆分每一行以获得我感兴趣的那三个部分。然后我使用 f-string 构建了我的新行。

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

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