FAQ: String Methods - Splitting Strings II


#1

This community-built FAQ covers the “Splitting Strings II” exercise from the lesson “String Methods”.

Paths and Courses
This exercise can be found in the following Codecademy content:

Computer Science

FAQs on the exercise Splitting Strings II

There are currently no frequently asked questions associated with this exercise – that’s where you come in! You can contribute to this section by offering your own questions, answers, or clarifications on this exercise. Ask or answer a question by clicking reply (reply) below.

If you’ve had an “aha” moment about the concepts, formatting, syntax, or anything else with this exercise, consider sharing those insights! Teaching others and answering their questions is one of the best ways to learn and stay sharp.

Join the Discussion. Help a fellow learner on their journey.

Ask or answer a question about this exercise by clicking reply (reply) below!

Agree with a comment or answer? Like (like) to up-vote the contribution!

Need broader help or resources? Head here.

Looking for motivation to keep learning? Join our wider discussions.

Learn more about how to use this guide.

Found a bug? Report it!

Have a question about your account or billing? Reach out to our customer support team!

None of the above? Find out where to ask other questions here!


#2

The following throws the following error when run in python 3 interpreter:

Exception has occurred: AttributeError

‘tuple’ object has no attribute ‘split’

File "C:\dev\Py-1\Test\string_exercises.py", line 47, in <module> author_names = authors.split(",")
authors = "Audre Lorde,Gabriela Mistral,Jean Toomer,An Qi,Walt Whitman,Shel Silverstein,Carmen Boullosa,Kamala Suraiyya,Langston Hughes,Adrienne Rich,Nikki Giovanni"

author_names = authors.split(',')

print(author_names)

author_last_names = []
for name in author_names:
  author_last_names.append(name.split()[-1])
  
print(author_last_names)

#3

code from the error message:

author_names = authors.split(",")

doesn’t match the code you posted:

author_names = authors.split(',')

the error message says authors is a tuple, if i attempt to run the code:

https://repl.it/@stetim94/InsubstantialUglyBlackpanther

it goes fine. So not sure what goes wrong


#4

Just a small tip in terms of cleanliness, this can be achieved using a simple list comprehension:

author_last_names = [name.split()[-1] for name in author_names]

#5

For the negative index, what is that mean? author_last_names.append (i.split()[-1])

In the script, I try below, but i still don’t know why and how it works. Please inform. Thank you
if [0] return first name. [-1] or [1] return last name.


#6

we can use negative indexes to access the list from the right hand side, so -1 is the right most element in a list or string:

print ['a', 'b', 'c', 'd'][-1] #output: d

so -2 would give c


#7

I see. Thank you so much