-1

I am checking for single quotation (') and printing its index, output is always 0

S="'abc','dsd''eeee'"
for i in S:
    if(i=="'"):
        print(S.index (i))

how to get 0,4....?

wjandrea
  • 28,235
  • 9
  • 60
  • 81

3 Answers3

1

str.index() only finds the first occurrence. Use enumerate instead.

for idx, i in enumerate(S):
    if i == "'":
        print(idx)

See Accessing the index in 'for' loops?

wjandrea
  • 28,235
  • 9
  • 60
  • 81
1

You can use the re regular expression library for matching:

import re
pattern = r"'"
text = "'abc','dsd''eeee'"
indexes = [match.start() for match in re.finditer(pattern, text)]
Josh
  • 136
  • 6
1

Here is a one-liner using list comprehension -

S="'abc','dsd''eeee'"
[i[0] for i in enumerate(S) if i[1] == "'"]
[0, 4, 6, 10, 11, 16]
Akshay Sehgal
  • 18,741
  • 3
  • 21
  • 51