Book Image

Mastering Python High Performance

Book Image

Mastering Python High Performance

Overview of this book

Table of Contents (15 chapters)

String concatenation


Python strings deserve a separate portion of this chapter because they're not like strings in other languages. In Python, strings are immutable, which means that once you create one you can't really change its value.

This is a relatively confusing affirmation, since we're used to doing things such as concatenation or replacement on string variables. However, what the average Python developer doesn't realize is that there is a lot more going on behind the curtains than they think.

Since string objects are immutable, every time we do anything to change its content, we're actually creating a whole new string with new content and pointing our variable to that new string. So, we must be careful when working with strings to make sure we actually want to do that.

There is a very simple way to check the preceding scenario. The following code will create a set of variables with the same string (we'll write the string every time). Then, using the id function (which, in CPython, returns...