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

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Dolfinwu
    New Member
    • May 2021
    • 2

    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.


    Code:
    sentence = list(input('Please type a sentence: '))
    space = ' '
    
    for space in sentence:
        if space in sentence:
            space_position = sentence[space]
            print(space_position)
  • Banfa
    Recognized Expert Expert
    • Feb 2006
    • 9067

    #2
    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.

    Comment

    • SioSio
      Contributor
      • Dec 2019
      • 272

      #3
      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.
      Code:
      import re
      sentence = str(input("Please type a sentence:"))
      r = re.finditer("o",sentence)
      for e in r:
      	print (e.start())

      Comment

      • Vanisha
        New Member
        • Jan 2023
        • 26

        #4
        You can use the index() method of a list to get the position of a string in it. Here's an example:
        my_list = ['apple', 'banana', 'cherry', 'banana', 'date']
        position = my_list.index(' cherry')
        print(position) # Output: 2
        In the example above, index() method is used to find the position of the string "cherry" in the list my_list. The result is stored in the position variable, which is printed to the console.

        If you're want to learn new technologies, join Cetpa Infotech.
        Check out our website for more information.

        Comment

        Working...