Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Truncate zero characters from the end of a string

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?

like image 790
Olivier Melançon Avatar asked Dec 06 '25 04:12

Olivier Melançon


2 Answers

I'd suggest:

my_string[:-i] if i > 0 else my_string
like image 191
Don Avatar answered Dec 07 '25 18:12

Don


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.

like image 44
Yang Avatar answered Dec 07 '25 19:12

Yang