Python Forum

Full Version: replace in code vs literals
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
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?
Assuming that the semicolon that you are replacing is at the end of a line, you could do this:

text = text.replace (';\n', '\n')
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
does it handle triple quotes?