Are strings cached?

>>> a = "zzzzqqqqasdfasdf1234"
>>> b = "zzzzqqqqasdfasdf1234"
>>> id(a)
4402117560
>>> id(b)
4402117560

but

>>> c = "<a href="https://getridbug.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="113051">[email protected]</a>#$"
>>> d = "<a href="https://getridbug.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="644524">[email protected]</a>#$"
>>> id(c) == id(d)
False
>>> id(a) == id(b)
True

Why get same id() result only when assign string?

Edited: I replace “ascii string” with just “string”. Thanks for feedback

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

It’s not about ASCII vs. non-ASCII (your “non-ASCII” is still ASCII, it’s just punctuation, not alphanumeric). CPython, as an implementation detail, interns string constants that contain only “name characters”. “Name characters” in this case means the same thing as the regex escape w: Alphanumeric, plus underscore.

Note: This can change at any time, and should never be relied on, it’s just an optimization they happen to use.

At a guess, this choice was made to optimize code that uses getattr and setattr, dicts keyed by a handful of string literals, etc., where interning means that the dictionary lookups involved often ends up doing pointer comparisons and avoiding comparing the strings at all (when two strings are both interned, they are definitionally either the same object, or not equal, so you can avoid reading their data entirely).


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x