Get the App
SLTechnology News&Howtos  ›  Development  › 

How to create Python strings and what is the residence mechanism

Shulou Source: shulou.com Published: 2022-06-01 12:05:15 10月04日 Update

This article focuses on "how to create Python strings and what is the hosting mechanism". Interested friends may wish to take a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn "how to create Python strings and what is the residence mechanism".

String

A string is a basic data type in Python and an immutable sequence of characters.

String resident mechanism

Only one copy of the same and immutable string is saved. Different values are stored in the resident pool of the string. Python's resident mechanism keeps only one copy of the same string. Later, when the same string is created, it does not open up new space, but assigns the address of the string to the newly created variable.

Several situations of resident mechanism (interactive mode windows+r,cmd)

1. The length of the string is 0 or 1

2. A string that matches the identifier

3. Strings only reside at compile time, not at run time

B connects to abc before running, while c connects at run time, so c does not reside, opening up a new space

4. The integer number between [- 5256]

The intern method in sys forces two strings to point to the same object

PyCharm optimizes the string

A = 'abc%'

B = 'abc%'

Print (an is b) # True

Advantages and disadvantages of string resident mechanism

When the same string is needed, it can be taken directly from the string pool to avoid frequent creation and destruction, improve efficiency and save memory. Therefore, concatenating strings and modifying strings will affect performance.

When string concatenation is needed, it is recommended to use the join method of type str instead of +, because the join () method calculates the length of all strings first, then copies them, and new the object only once, which is more efficient than "+".

At this point, I believe you have a deeper understanding of "how to create Python strings and what is the residence mechanism". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

Tags: Characters strings mechanisms methods same run content object copy efficiency space type length variable learning different practical deeper frequent two Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Huawei OPPO Reno Docker Xiaomi macOS