FAQ: String Methods - Splitting Strings II


#21

amazing… but how does it work? ```
[::-1]


#22

One line: For each author name, split it by the spaces and select the last item in the resulting array:

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

e.g.
William Carlos Williams becomes [“William”, “Carlos”, “Williams”] once split.
We then select the last index using -1, which is “Williams” to get our answer.


#23

Hello everyone! So, to start with, this is my first time actually posting anything here, and I don’t really know if this is the right place to post this, but here goes. I already got through this stage, but I reaally don’t think I solved it in the most optimal of ways. I’d very much appreciate it if someone were to critique it. I came up with this solution on my own btw, no tips or anything so be gentle lol.

last_name = “”
authors = “Audre Lorde, William Carlos Williams, 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)

for name in range(0, len(author_names)):
current_name = author_names[name]
#print(current_name)
for letter in range(-1, -len(current_name), -1):
#print(current_name[letter])
#print(letter)
if current_name[letter] == " ":
last_name += current_name[letter + 1:] + " "
#print( “I found a space. I should stop here.”)
break
#print(last_name)

last_names = last_name.split(" ")
author_last_names =

for name in range(0, len(last_names)):
print(name)
author_last_names.append(last_names[name])

author_last_names.pop()
print(last_names)
print(author_last_names)


#24

If you are referencing -1 of a string it will return the last letter in the string, for example: str1 = ‘hello there’ , str1[-1] = e
if you are referencing -1 of a list containing strings it will return the last string in the list, for example: lst1 = [‘hello’, ‘there’] , lst1[-1] = there


#25

Hi, first time poster. I had to see the solution for this one, and was wondering how an alternative would work so I tried the below:

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

when I print author_last_names it prints each letter of the last names like: [‘L’, ‘o’, ‘r’, ‘d’, ‘e’, ‘M’, ‘i’, ‘s’, ‘t’, ‘r’, ‘a’, ‘l’, ‘T’, ‘o’, ‘o’, ‘m’, ‘e’, ‘r’, ‘Q’, ‘i’, ‘W’, ‘h’, ‘i’, ‘t’, ‘m’, ‘a’, ‘n’, ‘S’, ‘i’, ‘l’, ‘v’, ‘e’, ‘r’, ‘s’, ‘t’, ‘e’, ‘i’, ‘n’, ‘B’, ‘o’, ‘u’, ‘l’, ‘l’, ‘o’, ‘s’, ‘a’, ‘S’, ‘u’, ‘r’, ‘a’, ‘i’, ‘y’, ‘y’, ‘a’, ‘H’, ‘u’, ‘g’, ‘h’, ‘e’, ‘s’, ‘R’, ‘i’, ‘c’, ‘h’, ‘G’, ‘i’, ‘o’, ‘v’, ‘a’, ‘n’, ‘n’, ‘i’]

How would I correct this code?/Why does it split at each letter?

Thanks!


#26

because of [-1]. Which gives you the last letter of a string or list