Reputation: 180461
out = ("First Name,Last Name,Street Address,City,State,Zip Code",",")
I am trying to use re to split the string out into the following:
['First Name', 'Last Name', 'Street Address', 'City', 'State', 'Zip Code']
my output is:
['First', 'Name', 'Last', 'Name', 'Street', 'Address', 'City', 'State', 'Zip', 'Code']
How can I split the string and keep any substring contained inside apostrophes grouped together.
I have very little experience using re so any help would be great. Thanks.
my code:
import re
def split_string(source, splitlist):
"""
:param source:
:param splitlist:
"""
splitlist= re.findall("[\w]+|[*]",source)
return splitlist
Upvotes: 1
Views: 370
Reputation: 251031
You can simply use str.split()
here:
In [41]: out = ("First Name,Last Name,Street Address,City,State,Zip Code",",")
In [42]: for x in out:
....: if x.replace(",",""): #check if the string is not empty
....: print x.split(",")
....:
['First Name', 'Last Name', 'Street Address', 'City', 'State', 'Zip Code']
using re.split()
:
In [10]: strs='First Name,Last Name,Street Address,City,State,Zip Code'
In [11]: re.split(r',',strs)
Out[11]: ['First Name', 'Last Name', 'Street Address', 'City', 'State', 'Zip Code']
Upvotes: 2
Reputation: 7949
Maybe you should just use out.split(",")
instead of re? Unless it's for a specific exercise...
Upvotes: 1