Reputation: 1145
I have a string of variable length and I know the index position is 25. As it's variable in his length (>= 25), I need a way to locate the negative index of that same position for easier data manipulation.
Do you have any idea how this can be done?
Upvotes: 2
Views: 92
Reputation: 1944
Lets use a 'list' with following values: '1', '2', '3','4', '5', '6'
Steps to get the negative index of any value:
Step1. Get the 'normal_index' of the value. For example the normal index of value '4' is 3.
Step2. Get the 'count' of the 'list'. In our example the 'list_count' is 5.
Step3. Get Negative index of the requested value. negative_index = (normal_index - list_count) - 1. Which is -3.
Upvotes: 1
Reputation: 37249
I'm not sure if this is what you're after, but if you have the index of a string, the 'negative' index is just the negative of the length of the string minus the index:
In [1]: import string
In [2]: s = string.ascii_letters
In [3]: s
Out[3]: 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
In [4]: s[25]
Out[4]: 'z'
In [5]: -(len(s)-25)
Out[5]: -27
In [6]: s[-(len(s)-25)]
Out[6]: 'z'
Or using the example from the comments:
In [7]: s = range(1, 7)
In [8]: s[4]
Out[8]: 5
In [9]: neg = -(len(s)-4) # Here you would replace 4 with your index
In [10]: s[neg]
Out[10]: 5
Upvotes: 2