首页 > 解决方案 > Python字符串指针?

问题描述

是否可以在 Python 中创建一个指针以在其他地方更改该字符串后使该变量等于该字符串?像下面这样的概念:

a = 'hello'
b = a
a = 'bye'

print(b) # is it possible have b be 'bye' without simply doing b = a again?

标签: pythonstring

解决方案


正如评论中指出的(以及它指向的链接),您最初拥有aandb都指向 string 'hello',但重新分配a不会影响b,它仍将指向 string 'hello'

实现您想要的一种方法是使用更复杂的对象作为字符串的容器,例如字典:

a = {'text': 'hello'}
b = a
a['text'] = 'bye'
print(b['text']) # prints 'bye'

推荐阅读