Python Forum

Full Version: Regex won't replace character with line break
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
using python 3.8.1

I am trying to write a string to a csv file. Before I write the string, however, I want to add line breaks into the string.

mystring is a set of values separated by ','. I want to include a line break at every instance there is a number exactly next to a capital letter. e.g(Text,10,0.0Text,9,8.0Text,5.45,2.3) etc..
I want it to write to the csv as:
Text,10,0.0
Text,9,8.0
Text,5.45,2.3

I have tried this so far but to no avail.

newstring = re.sub(r'[0-9][A-Z]', r'[0-9][A-Z]\n', mystring)

with open('new.csv', 'a') as file:
file.write(newstring)

This writes the string to the csv file but there are no line breaks it is all on the first line.

I would appreciate if someone can point me in the right direction.
Try this perhaps
import re

s = "Text,10,0.0Text,9,8.0Text,5.45,2.3"
new = re.sub(r'(?<=[0-9])(?=[A-Z])', '\n', s)
print(new)
Output:
Text,10,0.0 Text,9,8.0 Text,5.45,2.3
Finally, learn regexes!
(Jan-11-2020, 11:47 PM)Gribouillis Wrote: [ -> ]Try this perhaps
import re

s = "Text,10,0.0Text,9,8.0Text,5.45,2.3"
new = re.sub(r'(?<=[0-9])(?=[A-Z])', '\n', s)
print(new)
Output:
Text,10,0.0 Text,9,8.0 Text,5.45,2.3
Finally, learn regexes!

Thanks, I actually managed to find my own workaround which was to separate the string into a nested list which each line being its own list. I was then able to write it into the csv line by line using a for loop. Probably not the best way so I will try implement your suggestions. :)