Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

วิธีเปลี่ยน ID ของ Immutable String ใน Python

String ใน Python เป็น immutable ไม่สามารถเปลี่ยนแปลงได้หลังสร้าง

Python ใช้ string interning สตริงเดียวกันอาจชี้ไปที่หน่วยความจำเดียวกัน

ตัวอย่าง interning

>> a = 'hi'
>>> b = 'hi'
>>> id(a)
43706848
>>> id(b)
43706848  # id เหมือนกัน

แต่ไม่ guarantee ว่าจะ interning ทุกกรณี สตริงที่มี special characters อาจไม่ interning

ตัวอย่าง id ต่างกัน

>> a = 'weworks_45#@$'
>>> b = 'weworks_45#@$'
>>> id(a)
96226208
>>> id(b)
91720800  # id ต่างกัน