Hex
Hex

Reputation: 23

Was trying to get it to return the index value of multiple instances of the same character rather than just the first, can't figure out what happened

So, was just trying to see if I could figure out a way to get it to print the index value of not only the first "o" character, but also the second, so the output would clearly have to be 4, 8.

string = "Python for Beginners"
x = "o"
for x in string:
    print (string.index (x))

My reasoning being that for every character equal to "o" in the string, it would give me its specific index count. Instead, it gave me this as an output

0
1
2
3
4
5
6
7
4
9
6
11
12
13
14
5
5
12
9
19

So other than not doing what I thought it would, I've spent most of the past hour trying to figure out the logic that got me that output but alas, being a noob, I couldn't figure it out for the life of me. I'd be interested in a solution on how to get it to count multiple instances of the same character, but even more interested in understanding exactly what happened to give me that output. Just can't figure it out. Cheers all

Upvotes: 1

Views: 217

Answers (1)

Hex
Hex

Reputation: 23

OK so with a bit of diggin arouund i found of the re.finditer command which first requires us to import re (regular expression). I actually have no idea what that means but figured out enough to use it. Credit to this thread Finding multiple occurrences of a string within a string in Python Then just played around a bit but finally got it down to this

string = "Python for Beginners"
import re
search = input ("What are you looking for? ")
msg = f" '{search}' found at index: "
for x in re.finditer (search , string):
    print (msg, x.start())
if string.find (search) == -1:
    print ("Error: sequence not present in string. Note: search is case sensitive")

This is all just for the purposes of educating myself practically a little bit as I go through the learning. Cheers all. Still open to suggestions for "better ways" of achieving the same output.

Upvotes: 1

Related Questions