I have a string line and tried split with the delimiter ','
tp = 'A,B,C,"6G,1A",1,2\r\n'
tp.split(',')
and get the results as with the length of 7
['A', 'B', 'C', '"6G', '1A"', '1', '2\r\n']
but I want to get the result as to get the length 6
['A', 'B', 'C', '"6G,1A"', '1', '2\r\n']
how can I do that?
CodePudding user response:
https://docs.python.org/3/library/csv.html#csv.reader
>>> import csv
>>> tp = 'A,B,C,"6G,1A",1,2\r\n'
>>> r = list(csv.reader([tp]))
>>> r
[['A', 'B', 'C', '6G,1A', '1', '2']]
CodePudding user response:
You can use regex, in fact, once you know how to use regex.
It is much faster and easier for you to extract text.
tp = 'A,B,C,"6G,1A",1,2\r\n'
import re
ab = [s for s in re.split("(,|\\\".*?\\\"|'.*?')", tp)if s.strip(",")]
print(len(ab))
print(ab)
6
['A', 'B', 'C', '"6G,1A"', '1', '2\r\n']