468,467 Members | 2,667 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 468,467 developers. It's quick & easy.

How do I get the position of a string inside a list in Python?

I am trying to get the position of a string inside a list in Python? How should I do it?

For example, when a user provides a sentence "Hello my name is Dolfinwu", I turn the entire sentence into a list beforehand, and I want to get the positions of each "o" right here, how can I do it? In this case, the position of the first "o" is "4", and the position of the second "o" is "18". But obviously, users would enter different sentences by using different words, so how can I get a specific string value's position under this unpredictable situation?

I have tried this code as below. I know it contains syntax errors, but I could not figure out something better.

Expand|Select|Wrap|Line Numbers
  1. sentence = list(input('Please type a sentence: '))
  2. space = ' '
  4. for space in sentence:
  5.     if space in sentence:
  6.         space_position = sentence[space]
  7.         print(space_position)
4 Weeks Ago #1
2 3704
9,052 Expert Mod 8TB
a. Don't convert the string to a list, that isn't helpful
b. Use either the find or index method on the string depending on how you wish to handle errors (https://docs.python.org/2/library/string.html)
c. Consider using raw_input instead of input so that you always have a string.
3 Weeks Ago #2
246 128KB
When searching for a character string using the "find" method or "index" method, there may be multiple search character strings, so it is necessary to search while shifting the start position in a loop.
In such cases, the "finditer" method is useful.
Expand|Select|Wrap|Line Numbers
  1. import re
  2. sentence = str(input("Please type a sentence:"))
  3. r = re.finditer("o",sentence)
  4. for e in r:
  5.     print (e.start())
3 Weeks Ago #3

Post your reply

Sign in to post your reply or Sign up for a free account.

Similar topics

5 posts views Thread by olaufr | last post: by
12 posts views Thread by Anoop | last post: by
4 posts views Thread by Michael Yanowitz | last post: by
1 post views Thread by beginner | last post: by
reply views Thread by NPC403 | last post: by
1 post views Thread by kmladenovski | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.