Ivan Ivanyuk
Ivan Ivanyuk

Reputation: 115

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?

Upvotes: 3

Views: 12128

Answers (1)

zondo
zondo

Reputation: 20366

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

Upvotes: 11

Related Questions