how to separate the strings in a string
Peter Otten
__peter__ at web.de
Fri Apr 2 06:38:37 EDT 2021
On 02/04/2021 11:16, Egon Frerich wrote:
> I have a string like
>
> '"ab,c" , def'
>
> and need to separate it into
>
> "ab,c" and "def".
>
> split separates at the first ',':
>
>>>> bl
> '"a,bc", def'
>>>> bl.split(',')
> ['"a', 'bc"', ' def']
>
The initial string looks like it's close enough to the CSV format.
Unfortunately Python's csv module operates on files, not strings -- to
use it you have to wrap the string into a stream:
>>> import csv
>>> import io
>>> next(csv.reader(io.StringIO('"ab,c" , def')))
['ab,c ', ' def']
Apply str.strip() on every part to remove leading and trailing whitespace:
>>> def mysplit(s):
return [part.strip() for part in next(csv.reader(io.StringIO(s)))]
>>> mysplit('"ab,c" , def')
['ab,c', 'def']
More information about the Python-list
mailing list