Search code examples
pythonlistposition

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.

sentence = input('Please type a sentence: ')
space = ' '

for space in sentence:
    if space in sentence:
        space_position = sentence[space]
        print(space_position)

Solution

  • This code of yours is messed up a bit

    
    space = ' ' #  This is fine but redundant 
    for space in sentence: # Shouldn't reuse variable names. Should be <for char in sentence. But I wouldn't use that either since we don't need the char it self but the index
        if space in sentence: #Should be <if char == space> Your just returns a True if there's a single space anywhere in the string. Assuming it's using the correct variable named space. Honestly I don't know what this code will do since I didn't run it :P
            space_position = sentence[space]
            print(space_position)
    

    Here's what I would do, which could be done better but this has more clarity for someone learning.

    sentence = input('Please type a sentence: ')
    
    
    for i in range(len(sentence)):
        if sentence[i] == " ":
            print(i)
    
    #>>>Please type a sentence: A sentence and spaces
    #>>>1
    #>>>10
    #>>>14