获取 Python 中字符串的前 n 个字符的最佳方法

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

我需要获取 x 个字符的字符串的前 n 个字符,其中 n = x - len(endstring)endstring 可以有从 0 到 x.

的任意数量的字符

除了

之外,Python是否有更简洁、性能更好的方法来做到这一点
string[:len(string) - len(endstring)]

?

要点是 len(string) 看起来有点多余,但考虑到 endstring 个 0 个字符似乎是 "smoothest" 解决方案?

您可以改为 string[:-len(endstring) or None]