
On 22Mar2020 05:09, Steven D'Aprano <steve@pearwood.info> wrote:
I agree with Ned -- whether the string object is returned unchanged or a copy is an implementation decision, not a language decision.
[Eric]
The only reason I can think of is to enable the test above: did a suffix/prefix removal take place? That seems like a useful thing.
We don't make this guarantee about string identity for any other string method, and CPython's behaviour varies from method to method:
py> s = 'a b c' py> s is s.strip() True py> s is s.lower() False
and version to version:
py> s is s.replace('a', 'a') # 2.7 False py> s is s.replace('a', 'a') # 3.5 True
I've never seen anyone relying on this behaviour, and I don't expect these new methods will change that. Thinking that `is` is another way of writing `==`, yes, I see that frequently. But relying on object identity to see whether a new string was created by a method, no.
Well, ok, expressed on this basis, colour me convinced. I'm not ok with not mandating that no change to the string returns an equal string (but, really, _only_ because i can do a test with len(), as I consider a test of content wildly excessive - potentially quite expensive - strings are not always short).
If you want to know whether a prefix/suffix was removed, there's a more reliable way than identity and a cheaper way than O(N) equality. Just compare the length of the string before and after. If the lengths are the same, nothing was removed.
Aye. Cheers, Cameron Simpson <cs@cskk.id.au>