Reputation: 39
I have been trying to create a tiny script that takes scrambled text from a template and finds a location. I have even managed to make it work by trial and error. Problem is.....I don't know how it works. Maybe someone can clarify it for me ? Here's the code:
word_list = """something
Location: City
other_something"""
word_list = word_list.split()
indexes = [(index + 1) for index in range(len(word_list)) if word_list[index] == "Location:"]
location = []
location2 = []
for index in indexes:
location2 = location.append(word_list[index])
print location
After realising that name of the city always comes after the phrase "Location:" I wanted python to find and print the next word. It even works ! Now the part I don't get is why the location2 stays empty. To my understanding it should be equal to location. Or not ? Why the answer stays withing the Location ? Please note that I am a complete beginner so an answer that won't be very simple might be beyond my comprehension.
Upvotes: 1
Views: 70
Reputation: 1047
you can take advantage of a list's .index()
attribute,
word_list = """something
Location: City
other_something""".split()
print word_list[word_list.index('Location:')+1]
this will simply print 'City'
in this situation. index()
returns the index of the element specified by the first argument. By adding one to the index of 'Location'
, you can access the next element of the word_list
, which will always be the location if the format of the word_string
does not change.
Upvotes: 1
Reputation: 104
I hope this makes sense, this code is a bit wacky.
# This line of code assigns a value to the variable word_list
word_list = """something
Location: City
other_something"""
# This line makes a list from the words, with each item in the list being one word
word_list = word_list.split()
# This line loops the variable index over the range of the word_list, and if the index's value is "Location:" it stores
# index+1 into a list called indexes
indexes = [(index + 1) for index in range(len(word_list)) if word_list[index] == "Location:"]
# This makes an empty list called location
location = []
# This makes an empty list called location2
location2 = []
# This loops over the indexes in indexes
for index in indexes:
# This line of code never stores anything to location2, because location.append appends to the list called
# 'location', and since location.append does not return a value to store, location2 remains empty
location2 = location.append(word_list[index])
# This line prints the list called location.
print location
Upvotes: 1