'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
Solution 1:[1]
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
Solution 2:[2]
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]
Solution 3:[3]
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Ynjxsjmh |
| Solution 2 | |
| Solution 3 | S.B |
