python - Python字符串指针?
问题描述
是否可以在 Python 中创建一个指针以在其他地方更改该字符串后使该变量等于该字符串?像下面这样的概念:
a = 'hello'
b = a
a = 'bye'
print(b) # is it possible have b be 'bye' without simply doing b = a again?
解决方案
正如评论中指出的(以及它指向的链接),您最初拥有a
andb
都指向 string 'hello'
,但重新分配a
不会影响b
,它仍将指向 string 'hello'
。
实现您想要的一种方法是使用更复杂的对象作为字符串的容器,例如字典:
a = {'text': 'hello'}
b = a
a['text'] = 'bye'
print(b['text']) # prints 'bye'
推荐阅读
- sql-server - 如何将 mdf 文件导入 Azure Data Studio
- selenium - 无法在 intellij 中打开日志文件
- tfs - 与 Internet 断开连接时将 Visual Studio 2019 连接到 TFS 2010 时出现问题
- excel - Excel数据透视表日期分组问题
- javascript - Javascript - 控制台中出现意外的标识符错误消息
- json - Powershell JSON 到 CSV 的转换和导出
- python - django 注释调用是懒惰的吗?
- javascript - 加载本地音频文件并使用 Audio() 播放
- sql - 选择值以创建具有可选外键的唯一行
- r - 1:maxResults 中的错误:gdscrapeR 中长度为 0 的参数