![]() Here we get our first glimpse at the immutable nature of Python strings. TypeError: 'str' object does not support item assignment Let’s see what happens if we try to mutate a string directly in Python: # create a string Rather, we are simply reassigning a new value to the variables s1. It seems like we are mutating a string but really we are not. Here we see additional text added to the s1 variable. Let’s see how Python handles it: # Create an example string In most other programming languages it would be insane to consider doing such an operation to a string. This is confirmed via the output from the 2 print statements. This shows a variable a being assigned an integer value of 5 then, via the += operator (equivalent to a = a + 1) the value is “incremented” by 1 resulting in a final value of 6. Consider the following example: # example of number mutability ![]() However, this point is so essential to understanding how strings are stored and accessed in Python that it must be discussed. This is not an example of multiplying, adding, or subtracting strings.
0 Comments
Leave a Reply. |