It often happens that we need to truncate the end of a string by a certain amount. The correct way to do this is my_string[:-i].
But if your code allows i to be 0, this tuncate the whole string. The solution I generally use is to do my_string[:len(my_string)-i], which works perfectly fine.
Although I have always found that a bit ugly. Is there a more elegant way to achieve that behaviour?
I'd suggest:
my_string[:-i] if i > 0 else my_string
Maybe my_string[:-i or None]?
Because -0 equals to 0, maybe it is more elegent way to convert 0 into None, that's the solution above.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With