Did you know about String In Python?? By-(SparshVermatalks)<<>>Happy_learning

 Do you really think you know strings in Python?😮

 I was set to explore how strings are implemented in Python. The results were overwhelming. I realized that how little I knew about different string concepts and optimizations in Python.

What's more fascinating is that a lot of programmers are unaware of these concepts.

Okay, I'll begin with a simple snippet that I ran in my Python-3 interpreter:-

>>> a = "wtf" >>> b = "wtf" >>> a is b True >>> a = "wtf!" >>> b = "wtf!" >>> a is b False >>> a, b = "wtf!", "wtf!" >>> a is b True

Makes sense, right?

Well if it doesn't, hold on. Everything will feel obvious after a while. But before we do so, let me throw my next snippet at you:-

>>> a = "some_string" >>> id(a) 140420665652016 >>> id("some" + "_" + "string") # Notice that both the ids are same. 140420665652016

Alright, one final attack:--

>>> 'a' * 20 is 'aaaaaaaaaaaaaaaaaaaa' True >>> 'a' * 21 is 'aaaaaaaaaaaaaaaaaaaaa' False

None of these outcomes would have made sense to me a couple of weeks ago, and seeing them, I'd have faced an existential crisis as a regular Python programmer.

Anyway, if you have no idea what's going on here, every outcome is just a consequence of a concept called "String interning" here...

So whats is "String Interning"?

" Well' String Interning is a method of storing only one copy of each distinct String Value, which must be immutable "

String interning is the method of caching particular strings in memory as they are instantiated. The idea is that, since strings in Python are immutable objects, only one instance of a particular string is needed at a time. ... No new string objects are instantiated....




Comments

Popular Posts