首页 > 解决方案 > 在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',这就是我正在寻找的任何人都可以帮助我解决这个问题。

标签: python

解决方案


使用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)

推荐阅读