Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
replace in code vs literals
#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


Messages In This Thread
replace in code vs literals - by Skaperen - Mar-28-2021, 12:38 AM
RE: replace in code vs literals - by BashBedlam - Mar-28-2021, 02:13 AM
RE: replace in code vs literals - by ibreeden - Mar-28-2021, 11:11 AM
RE: replace in code vs literals - by Skaperen - Mar-30-2021, 12:37 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  What Are Python Literals? Julie 11 4,514 Sep-23-2020, 05:31 PM
Last Post: Gribouillis
  string literals in a list. Not what I expected. tycarac 3 2,700 Dec-28-2019, 05:31 AM
Last Post: tycarac
  parenthesis around a tuple of literals in a for Skaperen 2 2,201 Aug-25-2019, 03:00 AM
Last Post: Skaperen
  Search & Replace - Newlines Added After Replace dj99 3 3,428 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 11,982 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