Since I would not be able to sleep until I chose the best right answer, I tested the performance of each answer using two different scenarios in addition to what was provided by @jonrsharpe.
This is the code I used to compare performance between three different solutions using profile :
import profile arr='test 123456789014' def jonrsharpe(index): global arr for c in range(1,100000,1): a=arr[:-index if index else None] def Cyber(index): global arr for c in range(1,100000,1): a=arr[:len(arr)-index] def shashank(index): global arr for c in range(1,100000,1): a=arr[:-index or None] def testf(): for index in (0,3,6,9): jonrsharpe(index) Cyber(index) shashank(index) if __name__ == '__main__': profile.run("testf()")
Here is the result:
ncalls tottime percall cumtime percall filename:lineno(function) 799992 1.629 0.000 1.629 0.000 :0(len) 12 0.021 0.002 0.021 0.002 :0(range) 1 0.006 0.006 0.006 0.006 :0(setprofile) 1 0.000 0.000 4.390 4.390 <string>:1(<module>) 0 0.000 0.000 profile:0(profiler) 1 0.000 0.000 4.396 4.396 profile:0(testf()) 4 2.114 0.529 3.750 0.937 test.py:12(Cyber) 4 0.307 0.077 0.313 0.078 test.py:19(shashank) 1 0.000 0.000 4.390 4.390 test.py:26(testf) 4 0.319 0.080 0.328 0.082 test.py:5(jonrsharpe)
Another method:
import time if __name__ == '__main__': arr = '01234567890123456789012345678901234567890123456789'
Conclusion:
index= 0 jonrsharpe= 0.4918 Cyber = 0.5341 shashank = 0.4269 index= 10 jonrsharpe= 0.4617 Cyber = 0.5334 shashank = 0.4105 index= 20 jonrsharpe= 0.4271 Cyber = 0.4562 shashank = 0.3493 index= 30 jonrsharpe= 0.4217 Cyber = 0.4548 shashank = 0.3264 index= 40 jonrsharpe= 0.4713 Cyber = 0.8488 shashank = 0.6458 index= 49 jonrsharpe= 0.6159 Cyber = 0.5663 shashank = 0.4312
Since I will use this line of code millions of times, performance is very important, and @Shashank's solution was a winner in most cases, even if it was a little.
source share