Python Forum
Regex won't replace character with line break
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Regex won't replace character with line break
#1
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.
Reply
#2
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!
Reply
#3
(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. :)
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  break print_format lengthy line akbarza 4 275 Mar-13-2024, 08:35 AM
Last Post: akbarza
  Regex replace in SQLite3 database WJSwan 1 749 Dec-04-2023, 05:55 PM
Last Post: Larz60+
  Writing string to file results in one character per line RB76SFJPsJJDu3bMnwYM 4 1,306 Sep-27-2022, 01:38 PM
Last Post: buran
  regex multi-line kucingkembar 6 1,444 Aug-27-2022, 10:27 PM
Last Post: kucingkembar
  python-docx regex: replace any word in docx text Tmagpy 4 2,139 Jun-18-2022, 09:12 AM
Last Post: Tmagpy
  How can I add an end line character after every value that I receive? GiggsB 11 5,018 Mar-06-2022, 08:51 PM
Last Post: GiggsB
  [SOLVED] Why does regex fail cleaning line? Winfried 5 2,409 Aug-22-2021, 06:59 PM
Last Post: Winfried
  Regex: a string does not starts and ends with the same character Melcu54 5 2,367 Jul-04-2021, 07:51 PM
Last Post: Melcu54
  [solved] unexpected character after line continuation character paul18fr 4 3,294 Jun-22-2021, 03:22 PM
Last Post: deanhystad
  Find and replace in files with regex and Python Melcu54 0 1,824 Jun-03-2021, 09:33 AM
Last Post: Melcu54

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020