This question already has answers here:
About the changing id of an immutable string
(5 answers)
Closed 8 years ago.
In Interactive mode of python, When i say,
>>> mystr = 'abc'
we have object created in the current frame of type string with content 'abc'
Now, If i change the binding of mystr as shown below,
>>> mystr = 'def'
then, the name mystr will bind to a new object with the content 'def'.
We know that string are immutable objects, so object containing 'abc' gets unaffected.
In my machine it works like this:
>>> mystr = 'abc'
>>> id(mystr)
30868568
>>> mystr = 'def'
>>> id(mystr)
36585632
>>> mystr = 'abc'
>>> id(mystr)
30868568
My question:
How does Python environment deal with object containing 'abc' after new binding, Will it purged?
Strings are mutable, references are not.
When you assign str to "def", the other string "abc" does not affects. Just str's content will change, and it will reference to new "def" object.
When you manipulate strings in python, java etc.. languages such taking substring, it will make a new string object.
-For extra information (performance tips) if you work with strings for manipulating them use StringBuilder.
Related
This question already has answers here:
What are the rules for cpython's string interning?
(2 answers)
Python string interning
(2 answers)
Why and where python interned strings when executing `a = 'python'` while the source code does not show that?
(1 answer)
Closed last year.
When you assign same string literal to two variables, Python only allocates one string. This is very reasonable since string is immutable object in Python.
>>> a = "Hello"
>>> b = "Hello"
>>> id(a)
4311984752
>>> id(b)
4311984752
>>> a is b
True
But the strange part is: when the string contains special character (like !), Python will allocate two strings with exact same content.
>>> a = "hi!"
>>> b = "hi!"
>>> id(a)
4328663024
>>> id(b)
4317237616
>>> a is b
False
I read about this strange behaviour from here: https://python-course.eu/python-tutorial/data-types-and-variables.php
But that guide didn't elaborate why Python does this seemingly unnecessary duplicated string allocation.
My question is what's rationale behind Python's design of duplicated string allocation for string containing special character?
This question already has answers here:
python: why does replace not work?
(2 answers)
Closed 1 year ago.
a = 'dog'
a.replace('dog', 'cat')
print (a)
Really basic question, the function seems to be fairly straightforward but it just isn't replacing in this instance for some reason - is it because replace doesn't inherently change "a"?
Yes, you are correct. It won’t modify a.
Replace function will return a replaced string.
So, if you like to replace the text in a. Use the below code.
a = 'dog'
a = a.replace('dog', 'cat')
print (a)
Strings are immutable data types in Python which means that its value cannot be updated. Variables can point at whatever they want.
str.replace() creates a copy of string with replacements applied. See documentation.
Need to assign a new variable for the replacement.
a = 'dog'
b = a.replace('dog', 'cat')
print(b)
Output:
cat
This question already has answers here:
'is' operator behaves differently when comparing strings with spaces
(6 answers)
About the changing id of an immutable string
(5 answers)
Closed 8 years ago.
>>> s1 = "spam"
>>> s2 = "spam"
>>> s1 is s2
True
>>> q = 'asdalksdjfla;ksdjf;laksdjfals;kdfjasl;fjasdf'
>>> r = 'asdalksdjfla;ksdjf;laksdjfals;kdfjasl;fjasdf'
>>> q is r
False
How many characters should have to s1 is s2 give False? Where is limit? i.e. I am asking how long a string has to be before python starts making separate copies of it.
String interning is implementation specific and shouldn't be relied upon, use equality testing if you want to check two strings are identical.
If you want, for some bizarre reason, to force the comparison to be true then use the intern function:
>>> a = intern('12345678012345678901234567890qazwsxedcrfvtgbyhnujmikolp')
>>> b = intern('12345678012345678901234567890qazwsxedcrfvtgbyhnujmikolp')
>>> a is b
True
Here is a piece of comment about interned string from CPython 2.5.0 source file (stringobject.h)
/* ... ... This is generally restricted to strings that **"look like" Python identifiers**, although the intern() builtin can be used to force interning of any string ... ... */
Accordingly, strings contain only underscores, digits or alphabets will be interned. In your example, q and ``r contain ;, so they will not be interned.
This question already has answers here:
Aren't Python strings immutable? Then why does a + " " + b work?
(22 answers)
Closed 3 years ago.
I have declared a string "y as hello than tried to change character "h" by "m" using replace method in python and i checked for the type(y): its showing string
but when I googled, its showing strings are immutable... please explain
>>> y="hello"
>>> y=y.replace("h","m")
>>> y
'mello'
>>> type(y)
<class 'str'>
You didn't mutate the String, you changed what String y pointed to.
y originally pointed to "hello", then you ran the line y=y.replace("h","m") and caused y to instead point to the String "mello". The original String "hello" was never mutated, since Strings are indeed immutable.
Yes, strings are immutable. When you run the line
y=y.replace("h","m")
you are creating a new string, not changing the first one. The first string can't actually be changed.
String in Python are immutable (cannot change to allow for optimization of using one dictionary for all strings).
For example:
>>> y="hello"
>>> y.replace("h","m")
'mello'
>>> y
'hello'
When we want to change a string, we can either use bytearray or (often better) - just create a new string. Consider for example the method 'replace'. It did not change the string in the example - but we could assign it's return value.
>>> y1 = y.replace("h","m")
>>> y1
'mello'
Or even use the same variable y, in which case it will create a new string and overwrite the previous value of y.
>>> y = y.replace('h','m')
>>> y
'mello'
Which is just like putting a new value alltogether:
>>> y = 'a new value'
>>> y
a new value
This question already has answers here:
How do I create variable variables?
(17 answers)
Closed 7 years ago.
here is my python code:
>>> listName = 'abc'
>>> exec(listName+"=[]")
>>> print listName
>>> 'abc'
excepted output:
>>> print listName
>>> []
I want to define a new variable based on that string.
Even though that may be possible for global (and not local) variables, the better, cleaner, simpler, safer, saner (all in one word: pythonic) way is to use a dictionary for dynamic names:
values = {}
varname = get_dynamic_name()
# set
values[varname] = value
# get
values[varname]