Reputation: 25
I've been working with lists and arrays.In this task I need to return (in order) the sentence but instead of returning the sentence in order I need to return the positions the words are in, in order So here is my current code:
sentence = "Hello my name is Daniel, hello Daniel"
sentence = sentence.upper()
sentence = sentence.split()
list = sentence
which returns:
['HELLO', 'MY', 'NAME', 'IS', 'DANIEL,', 'HELLO', 'DANIEL']
but the desired out come is:
[0, 1, 2, 3, 4, 0, 4]
Does anyone know how I could get this outcome from the given code by adding more code to it?
Upvotes: 0
Views: 52
Reputation: 11477
It seems that you want to get Daniel
not Daniel,
so you should replace the comma or remove it.And then use index method to return the lowest index in list that obj appears.
sentence = "Hello my name is Daniel, hello Daniel"
sentence = sentence.replace(',','').upper()
sentence = sentence.split()
print [sentence.index(i) for i in sentence]
And it returns
[0, 1, 2, 3, 4, 0, 4]
Upvotes: 2