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 trialNantheesh P
1,260 PointsSplitting string into a list
text = "Ada&Jean&Grace&Margaret"
What if I wanted it to split after the & sign?
So that it returns: 'Ada&', 'Jean&', 'Grace&', 'Margaret'
Thank you,
3 Answers
Alexander Davison
65,469 PointsUnfortunately, there's no Python built-in method for that. But you can write your own function!
Grigorij Schleifer
10,365 PointsHi Nantheesh, here my suggestion, I am a python newbie and I guess there must be a more functional way to do this.
text = "Ada&Jean&Grace&Margaret"
def transform(text):
word = [] # keeps the temporary result until i is &
ls = [] # when & is found the word will be appendet to ls
for i in text:
word.append(i)
if i == "&":
ls.append(word)
word = [] # after append, word is emptied to be replaced with the next candidate
if word: # append the last word that has no &
ls.append(word)
return print(["".join(item) for item in ls])
transform(text)
Let us know what you think
Samuel Burke
1,467 PointsHello Nantheesh, If you want to split on the '&' symbol, and you want it removed, you can use the split method:
text = text.split('&')
This will make the text variable hold the following:
['Ada', 'Jean', 'Grace', 'Margaret']
I know this might not be what you are looking for, but you may find it helpful.
Alexander Davison
65,469 PointsUnfortunately, it seems that there's an extra "&" symbol after "Margaret", but there's no "&" after "Margaret" in the string itself!
Samuel Burke
1,467 PointsThanks, Alexander. I have removed that portion of the code.