Olivier Melançon
Olivier Melançon

Reputation: 22324

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?

Upvotes: 2

Views: 156

Answers (2)

Yang
Yang

Reputation: 91

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.

Upvotes: 3

Don
Don

Reputation: 17636

I'd suggest:

my_string[:-i] if i > 0 else my_string

Upvotes: 6

Related Questions