You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python中创建值相同但标识不同的两个字符串?

如何创建值相同但标识不同的Python字符串

Python的字符串驻留(interning)机制会自动复用内容相同的字符串字面量对象,这就是你之前各种方法都得到相同id的原因。要创建值相同但标识不同的字符串,需要绕开这种优化,以下是几种可行的方法:

方法1:通过编码-解码生成新对象

利用字符串编码为字节,再从字节解码为新字符串的方式,强制创建新对象:

firststr = 'blah blah blah'
# 编码后再解码生成新字符串
secondstr = firststr.encode('utf-8').decode('utf-8')

print(id(firststr))
print(id(secondstr))
print(firststr is secondstr)  # 输出 False
print(firststr == secondstr)  # 输出 True

方法2:动态拼接非字面量内容

如果字符串是通过变量动态拼接生成的,Python编译时无法提前确定结果,不会触发驻留:

prefix = 'blah '
firststr = prefix + 'blah blah'
secondstr = prefix + 'blah blah'

print(id(firststr))
print(id(secondstr))
print(firststr is secondstr)  # 输出 False

方法3:从IO流读取生成新字符串

通过IO类读取字符串内容,会生成全新的字符串对象:

from io import StringIO

firststr = 'blah blah blah'
with StringIO(firststr) as f:
    secondstr = f.read()

print(id(firststr))
print(id(secondstr))
print(firststr is secondstr)  # 输出 False

为什么你之前的方法无效?

  • str('blah blah blah' + ''):Python编译时会将'blah blah blah' + ''优化为原字面量,依旧会被驻留。
  • 'blah blah blah'[:]:对整个字符串切片时,Python会直接返回原对象的引用,不会创建新字符串。
  • copy.copy()/copy.deepcopy():字符串是不可变类型,copy模块对其直接返回原对象,不会生成副本。
  • 修改PyCharm变量加载策略:该设置和字符串驻留机制无关,因此没有效果。

内容的提问来源于stack exchange,提问作者Erfan Gholizadeh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.18 22:48:15