python - 在python中附加字符串而不更改变量名
问题描述
嗨团队有没有办法在python中附加字符串,我的意思是我需要全局声明变量并将字符串附加在一起并写入我的文件而不更改变量名。
例如
example_string = ''
def method1():
example_string = 'Value1'
def method2():
example_string = 'value2'
def method3():
example_string = 'value3'
print(example_string )
现在我希望我的结果打印为'Value1 value2 value3',这就是我正在寻找的任何人都可以帮助我解决这个问题。
解决方案
使用global
关键字更改函数中的全局变量。用于+=
附加到字符串。
example_string = ''
def method1():
global example_string
example_string += 'value1'
def method2():
global example_string
example_string += 'value2'
def method3():
global example_string
example_string += 'value3'
请注意,为了获得最后一个字符串,您需要调用所有三个函数
method1()
method2()
method3()
print(example_string)
推荐阅读
- ubuntu - 使用 QEMU 为基于 AM5728 ARM 的处理器构建 docker 镜像
- hadoop - 如何访问 scm 数据库并更改那里的服务状态?
- google-apps-script - 无法实施第三方 Google 日历会议插件
- ms-access - 在添加模式下打开表单,保存,然后置于编辑模式 - 刷新或重新查询?
- c# - 'Color' 是 'Xamarin.Forms.Color' 和 'Microsoft.Xna.Framework.Color' 之间的模糊引用
- javascript - 仅在用户停止键入后 JSF 2.1 Ajax 自动完成 + 服务器搜索
- windows - 如何让任务调度程序从 powershell 脚本中检测失败的错误代码
- httpclient - Angular 7 HttpClient 响应类型作为类
- python - python执行同步windows命令
- python - scipy的solve_ivp如何控制最大迭代次数?