0

eg ‘“Hello Word” = "hello world";’, '"Hello=Word" = "Hello=Word"',find the middle of the "=" position by python. I try this

>>>line = '"Hello=Word" = "Hello=Word"'
>>>index = line.index("=")
>>> index
6

I expect it return 13

Yt Lan
  • 41
  • 1
  • 5
  • The first `=` is at position 6... – Willem Van Onsem Mar 16 '17 at 13:08
  • 2
    What exactly is the logic here? Do you want the 2nd occurence of `'='`? The one in the middle? If so, what if there's an even number? Or maybe you want to find the first one that's not inclosed in quotes? There's a dozen ways to do this, but the question is which one is the most suitable. – Aran-Fey Mar 16 '17 at 13:10
  • Please, take a look on this http://stackoverflow.com/questions/11122291/python-find-char-in-string-can-i-get-all-indexes – MaxLunar Mar 16 '17 at 13:10

2 Answers2

1

Probably a case for using regexes.

import re
re.search(r'^".*".*(=).*".*"$', line).start(1)

This assumes the string is of the form you specified, with double-quote " delimited strings on either side of an =.

Denziloe
  • 7,473
  • 3
  • 24
  • 34
1

Actually, you can also look on all occurrences of = in string via enumerate(line). It returns you an enumerate object, which is iterable and contains tuples with format (index, item). So, that can be used like this:

>>> occurrences = [x[0] for x in enumerate(line) if x[1] == '=']
>>> occurrences
[6, 13, 21]

Now you should pick that index which you need.

MaxLunar
  • 653
  • 6
  • 24