3

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)
Dolfinwu
  • 262
  • 1
  • 14
  • Can you provide some more examples of expected inputs and outputs? What does the list representation look like? What would the expected output of "My name Hello" be? – mousetail Apr 22 '21 at 10:44
  • 3
    `print([(item, index) for index, item in enumerate(string) if item == 'o'])` something like this? – Matiiss Apr 22 '21 at 10:44
  • 3
    Does this answer your question? [How to find all occurrences of a substring?](https://stackoverflow.com/questions/4664850/how-to-find-all-occurrences-of-a-substring) – mousetail Apr 22 '21 at 10:44
  • Welcome to StackOverflow. Please post your code on how you have approached the problem, and what is not working. – rajah9 Apr 22 '21 at 10:45

3 Answers3

5

How about this one? I figured another solution out yesterday.

import re
sentence = input('Please type a sentence: ')
print([match.span()[0] for match in re.finditer(' ', sentence)])
Dolfinwu
  • 262
  • 1
  • 14
  • To get the onset of each occurrence, use re.finditer and extract the first item of the span attribute. – Dolfinwu May 19 '21 at 02:28
2

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 since I'm a beginner too.

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
pudup
  • 121
  • 5
  • List comprehension and things could prolly get the same result in one line but I imagine that will just confuse you. – pudup Apr 22 '21 at 11:42
  • For anybody reading this in the future, you could make this better with the enumerate function too. – pudup May 11 '21 at 12:51
0

There is also an error in your first code, where the line space_position = sentence[space] uses a string, if I am correct, as the index of the list in the line, which I believe should be an integer. So what I would do would be like

sentence = input('Please type a sentence: ')  # Asks the user to input the sentence
space_position = []  # The list where the list indexes of the spaces will be stored (can work for any other symbol)

for i in range(len(sentence)):  # Scans every single index of the list
    if sentence[i] == " ":  # Determines whether if the value of the specific list index is the chosen string value
    # (The value could be swapped for another one aside from strings)
        print(i)  # Print out the index where the value is the chosen string value

The rest of the cost are like what @pudup posted

P.S. I am also a beginner, so my code may not be the best solution or have syntax errors, apologies if they do not work or are not very efficient.

Jason0591
  • 59
  • 7