Python Forum
Regex won't replace character with line break - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Regex won't replace character with line break (/thread-23671.html)



Regex won't replace character with line break - Tomf96 - Jan-11-2020

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.


RE: Regex won't replace character with line break - Gribouillis - Jan-11-2020

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!


RE: Regex won't replace character with line break - Tomf96 - Jan-12-2020

(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. :)