0

To "peek" at characters in a string preceding the current index, i, is there a one-liner for avoiding negative indices? I want n chars before the current char index of the string OR beginning of the string to current char.

My intuition says there might be something simple I can put in the same line as the list operation instead of another line to make an index. I'd rather avoid any libraries, and I'm aware a simple if check would work... Hoping there's a magic operator I missed.


>>> s = 'ABCDEFG'
>>> s[0:5]
'ABCDE'
>>> s[-5:5]
'CDE'

Gino Mempin
  • 25,369
  • 29
  • 96
  • 135
123
  • 595
  • 6
  • 18

2 Answers2

3

There is no operator for doing this, but you can achieve the same effect with max:

>>> s = 'abcdefg'
>>> i = 3
>>> s[max(i - 6, 0):i + 2]
'abcde'
gmds
  • 19,325
  • 4
  • 32
  • 58
  • i think this is the answer, but abhilash got it just a few second earlier; i'll give them the answer. thanks for helping – 123 Aug 25 '20 at 23:19
2

How about this?

s = 'ABCDEFG'
i = 5
n = 3

print(s[max(0, i-n): i])

Output:

CDE
Abhilash
  • 2,026
  • 17
  • 21