1

I have an HTML object that contains a list if an 'X' is found I want to print the x and the next item in the list:

for string in tr[30].strings:
      if string == 'X':
              print(string)
              print(string.next())

Getting error:

TypeError: 'NavigableString' object is not callable

Lev
  • 999
  • 2
  • 10
  • 26
  • 1
    Possible duplicate of [Python - Previous and next values inside a loop](https://stackoverflow.com/questions/1011938/python-previous-and-next-values-inside-a-loop) – TemporalWolf Dec 05 '17 at 21:43
  • 2
    Much, *much* easier: track the previous item. Store each `string` into `previous` at the end of the loop, then just check `if previous == 'X':`, at which point `string` is the 'next' value after `'X'`. – Martijn Pieters Dec 05 '17 at 21:46
  • What happens if you do `string.next` instead of `string.next()`? – Acccumulation Dec 05 '17 at 21:56
  • 1
    It's worth noting none of the answers so far address `NavigableString` objects... so they may have a better option than the general approaches given. – TemporalWolf Dec 05 '17 at 22:20
  • @MartijnPieters I used your method and it worked flawlessly. >>> for string in tr[30].strings: ... if string != '\n': ... if previous == 'X': ... print(string) ... previous = string – Lev Dec 06 '17 at 06:26

2 Answers2

6

You can use enumerate, example:

strings = tr[30].strings 

for index, string in enumerate(strings):
    if string == 'X':
        print(string)
        print(strings[index + 1])
2

Try this:

theIterator = iter(tr[30].strings)

for string in theIterator:
      if string == 'X':
              print(string)
              print(next(theIterator))

But be aware that manipulating the iterator of a running for-loop is not recommend.

Michael Butscher
  • 10,028
  • 4
  • 24
  • 25