Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Stivan Radev
1,475 PointsPython split multiple delimiters
So I was able to go from this:
|g,zools|g,zoomgls|g,zorromystery|g,zunveo|g,zwaytu|g,zyc645691995|
to this:
g,zools
g,zoomgls
g,zorromystery
g,zunveo
g,zwaytu
g,zyc645691995
by using the following code:
text = "|g,zools|g,zoomgls|g,zorromystery|g,zunveo|g,zwaytu|g,zyc645691995|"
data = text.split("|")
print(data[0])
print(data[1])
print(data[2])
for temp in data:
print(temp)
But now as you can see I've got those "g," still there and I was wondering how can I split with multiple delimiters? I've tried text.split("|", "g,") but I'm getting this error TypeError: 'str' object cannot be interpreted as an integer. And now I'm stuck and I do not know what else I can try. Perhaps, .split() can only use 1 delimiter?
Thanks.
3 Answers
Steven Parker
243,656 PointsI'm not entirely sure what your objective is, do you want to remove the bar, the "g", and the comma? Then this should do it:
data = text.split("|g,")
Stivan Radev
1,475 PointsSteven Parker, that is exactly my objective. Another question: Say I've got these now:
"|g,zools|t,jim54352|tr,skate9353|l,tom11|"
can I pass multiple delimiters like this
data = text.split("|g,t,tr,l,")
So that I'm just left with
zools
jim54352
skate9353
tom11
Thanks.
Steven Parker
243,656 PointsThe "|g," argument in my answer is just one delimiter with multiple characters. It sounds like you need a function where you can create a "rule" for delimiters that would fit a number of them.
The re.split() function can do that, it's part of Python's regular expression library . There happens to be a related course here on Regular Expressions in Python.
Stivan Radev
1,475 PointsSteven Parker Thank you so much for your help !!!!