I have a multi-line string and need to append at the beginning of each row a (varying) character (1 white-space as separator). How can I do that with regex? Is there a way to do that without without too many splittings and merging?
It is assumed that the amount of rows is equal to the amount of characters to be added.
Input
m = """
0 1 2 3 4 5
1 0 1 2 3 4
2 1 1 2 3 4
"""
Desired output (assumed reference string "bip")
b 0 1 2 3 4 5
i 1 0 1 2 3 4
p 2 1 1 2 3 4
Here an example of working code based on \n match
import re
m = """
0 1 2 3 4 5
1 0 1 2 3 4
2 1 1 2 3 4
"""
re.sub(r'\n', '\n{} ', m[:-1]).format(*list('bip'))
but I needed to omit the last character, it would \n. I tried to play around with other pattern such as \A or \^ or ^, flags=re.MULTILINE but with no success.
How can I avoid the string slice m[:-1]?
Is there a more pure regex way to solve the problem?
Here is another approach using 4th parameter count of re.sub that tells how many substitutions are to be made:
As per linked doc:
re.sub(pattern, repl, string, count=0, flags=0)
Code:
import re
m = """
0 1 2 3 4 5
1 0 1 2 3 4
2 1 1 2 3 4
"""
repl = 'bip'
print (re.sub(r'\n', '\n{} ', m, len(repl)).format(*list(repl)))
# or use this if you want to strip leading and trailing newlines
# print (re.sub(r'\n', '\n{} ', m, len(repl)).format(*list(repl)).strip())
Code Demo
Output:
b 0 1 2 3 4 5
i 1 0 1 2 3 4
p 2 1 1 2 3 4
If you apply .strip() to your m string, you can use
import re
m = """
0 1 2 3 4 5
1 0 1 2 3 4
2 1 1 2 3 4
"""
print(re.sub(r'^', '{} ', m.strip(), flags=re.M).format(*list('bip')))
See the Python demo, the output will be
b 0 1 2 3 4 5
i 1 0 1 2 3 4
p 2 1 1 2 3 4
The ^ regex anchor will match any line start position since the flags argument is set to re.M (equivalent to re.MULTILINE).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With