1

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

Hex
  • 23
  • 6
  • Maybe try this first - `list(re.finditer(x, string))` – Daniel Hao Nov 01 '21 at 11:09
  • 1
    thanks. only saw the reply now. yes i went with re.finditer in the end, took me a bit to figure out but got the job done in the end. Thanks for taking the time – Hex Nov 01 '21 at 14:20
  • Welcome. You can post your own `answer` if you're able to get it. The others can learn from it. – Daniel Hao Nov 01 '21 at 14:39

1 Answers1

1

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.

Hex
  • 23
  • 6