简体   繁体   中英

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.

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:

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 = '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

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:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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