Python Forum
splitting a line with quoted whiespace
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
splitting a line with quoted whiespace
#1
i would like to split a line by whitespace into items where there may be items with quoted whitepace. for example i might have a string like this:
foo "a b 'c'" bar
and i would like to get a list equivalent to ["foo","a b 'c'","bar"]. this means parsing the line string with an understanding of whitespaces and quotes. anyone know anything that will strictly parse the line and safely bail out if is not just right? support for triple quotes is a plus but not required.
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
one way
import csv
line = """foo "a b 'c'" bar"""
rdr = csv.reader([line], delimiter=' ')
print(next(rdr))
Output:
['foo', "a b 'c'", 'bar']
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  email Library: properly send message as quoted-printable malonn 3 1,311 Nov-14-2022, 09:31 PM
Last Post: malonn
  EOF while scanning triple-quoted string literal louis216 1 3,930 Jun-30-2020, 04:11 AM
Last Post: bowlofred
  Subtract 11 from entire list of quoted numbers Pleiades 1 1,700 Nov-14-2019, 10:26 AM
Last Post: Larz60+
  using ' inside ''' quoted strings or " inside """ quoted strings Skaperen 2 2,419 Dec-27-2018, 04:37 AM
Last Post: Skaperen

Forum Jump:

User Panel Messages

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