Python Forum
replace in code vs literals - 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: replace in code vs literals (/thread-33084.html)



replace in code vs literals - Skaperen - Mar-28-2021

i have a string of Python code. i want to replace(';','\n') for the code but not for any ';' in literal strings. anyone have an idea how?


RE: replace in code vs literals - BashBedlam - Mar-28-2021

Assuming that the semicolon that you are replacing is at the end of a line, you could do this:

text = text.replace (';\n', '\n')



RE: replace in code vs literals - ibreeden - Mar-28-2021

I believe it is difficult to construct a regular expression to split the string on a semicolon and ignore semicolons in a quoted part of the string. One would need to build a parser, reading the string character by character, to do this right.
But wait! We have a parser for this: the CSV parser. The ugly thing is that the CSV module needs to read a file. So you would first write the string to a file and then read it using CSV.
But there is still a way that is a little less ugly: you can convert a string to a file object using io.StringIO.

import csv
from io import StringIO

command_string = '"thing";"thing2;thing3";"anotherthing"'
f = StringIO(command_string)
reader = csv.reader(f, delimiter=';')
for row in reader:
    result = '\n'.join(row)
print(result)
Output:
thing thing2;thing3 anotherthing



RE: replace in code vs literals - Skaperen - Mar-30-2021

does it handle triple quotes?