Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
replace in code vs literals
#1
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?
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply
#2
Assuming that the semicolon that you are replacing is at the end of a line, you could do this:

text = text.replace (';\n', '\n')
Reply
#3
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
Reply
#4
does it handle triple quotes?
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  What Are Python Literals? Julie 11 1,537 Sep-23-2020, 05:31 PM
Last Post: Gribouillis
  string literals in a list. Not what I expected. tycarac 3 1,223 Dec-28-2019, 05:31 AM
Last Post: tycarac
  parenthesis around a tuple of literals in a for Skaperen 2 956 Aug-25-2019, 03:00 AM
Last Post: Skaperen
  Search & Replace - Newlines Added After Replace dj99 3 1,793 Jul-22-2018, 01:42 PM
Last Post: buran
  Help with python code to search string in one file & replace with line in other file mforthman 26 6,465 Dec-19-2017, 07:11 PM
Last Post: Larz60+

Forum Jump:

User Panel Messages

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