Ivan Ivanyuk February 2016

Best way to get first n characters of the string in Python

I need to get first n characters of the string of x characters, where n = x - len(endstring) and endstring can have any number of characters from 0 to x.

Is there cleaner and better performance-wise way to do it in Python beside:

string[:len(string) - len(endstring)]

?

Main point is that len(string) looks a little redundant, but to account for endstring of 0 characters it seemed as the "smoothest" solution?

Answers


zondo February 2016

You can do string[:-len(endstring) or None] instead.

Post Status

Asked in February 2016
Viewed 3,368 times
Voted 11
Answered 1 times

Search




Leave an answer