how to separate the strings in a string

Peter Otten __peter__ at web.de
Fri Apr 2 07:26:50 EDT 2021


On 02/04/2021 12:38, Peter Otten wrote:
> 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']
> 

I forgot that the reader() accepts arbitrary iterables. Instead of 
io.StringIO(s) you can just write [s].




More information about the Python-list mailing list