0

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?

2
  • In your model, both 'DANIEL,' and 'DANIEL' are being represented by 4. Do you need to strip punctuation? Commented Feb 17, 2017 at 16:06
  • @mgilson in this case punctuation does not affect the outcome, so 'Daniel,' and 'Daniel' are treated as the same and should return the same position Commented Feb 17, 2017 at 16:08

1 Answer 1

2

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]
Sign up to request clarification or add additional context in comments.

4 Comments

thank you!!! Would this method work if the variable 'sentence' is a sentence inputted by the user?
@D.Forrester yeah.If this helps,please accept this answer.
sentence = sentence.replace(",",'"',"'").upper() AttributeError: 'list' object has no attribute 'replace' this error has occur when I made sentence into a user inputted variable. do you know why? @McGrady
@D.Forrester Make sure sentence is a string,and then use split() method.To get the input as a string,you should use raw_input in Python2 or input in Python3.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.