-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
  • 23,210
  • 7
  • 49
  • 68

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
  • 23,210
  • 7
  • 49
  • 68
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
  • 126
  • 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
  • 15,950
  • 2
  • 19
  • 40