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

如何在Python函数多次调用时累加字符串变量不覆盖原有值

问题:全局字符串变量无法实现累加

现有Python代码如下:

strings = None
def test(a):
    strings = str(strings) + f"{a}\n"

多次调用函数:

test("hello")
test("world")

目前strings仅保留最后传入的"world",需要实现字符串累加,最终得到:

hello
world

原因分析

函数内部直接赋值strings = ...时,Python会将其视为局部变量,而非修改全局的strings。每次调用函数时,局部的strings会被重新定义,导致之前的累加结果丢失。


解决方案

方法1:使用global声明全局变量

在函数内部用global关键字声明strings是全局变量,这样赋值时就会修改全局的strings,而不是创建局部变量:

strings = None
def test(a):
    global strings
    if strings is None:
        strings = ""  # 初始化空字符串,避免第一次拼接时出现"None"
    strings += f"{a}\n"

test("hello")
test("world")
print(strings)

运行后strings的值为:

hello
world

方法2:使用可变容器(如列表)存储字符串

因为字符串是不可变类型,每次拼接都会生成新对象,而列表是可变类型,直接修改更高效。可以用列表存储每一段字符串,最后再合并成一个完整的字符串:

strings = []
def test(a):
    strings.append(a)

test("hello")
test("world")
# 最后合并成带换行的字符串
result = "\n".join(strings) + "\n"
print(result)

这种方式避免了全局变量的使用,同时累加效率更高(尤其当拼接次数多的时候)。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 17:12:37