Expert Python Programming(Third Edition)
上QQ阅读APP看书,第一时间看更新

Implementation details

Python strings are immutable. This is also true for byte sequences. This is an important fact, because it has both advantages and disadvantages. It also affects the way strings should be handled in Python efficiently. Thanks to immutability, strings can be used as dictionary keys or set collection elements because, once initialized, they will never change their value. On the other hand, whenever a modified string is required (even with only tiny modification), a completely new instance needs to be created. Fortunately, bytearrayas a mutable version of bytesdoes not have such an issue. Byte arrays can be modified in-place (without creating new objects) through item assignments and can be dynamically resized, exactly like lists – using appends, pops, inserts, and so on.

Let's discuss string concatenation in the next section.