Say I have a big_string
of length n
and I want to remove a substring of length k
from its end
we can do it as big_string[:-k]
, but this will be of O(n-k)
, can we do better than this, something like inO(k)
?
Say I have a big_string
of length n
and I want to remove a substring of length k
from its end
we can do it as big_string[:-k]
, but this will be of O(n-k)
, can we do better than this, something like inO(k)
?
If your string is py2 unicode
or py3 str
, the memoryview
idea that @MyNameIsCaleb pointed to won't work, and slices will indeed make copies, which is O(n).
Trimming the end is fast for mutable types (del m[-k:]
), but only string types (which are immutable) support string operations like find()
, in
, and regular expressions.
If trimming the end is a very frequent operation, and using string operations is rare or can be bounded to a small portion of the string, it might be worth the trouble to convert the string once to a list of characters:
chars = [c for c in big_string]
To use string operations on bounded portions, you could convert a slice to a string. For example, to determine whether 'foo' occurs in the last 1000 characters:
'foo' in ''.join(chars[-1000:])