首页 > 解决方案 > Python:附加到一个空字符串

问题描述

我目前正在做一个项目,我想添加字符/gr

barfoo = ""
# Something that adds 'hel' to barfoo?
# Something that adds 'lo' to barfoo?
print(barfoo)
> 'hello'

我怎么会做这样的事情?请注意,我知道将它添加到列表中并简单地“压缩”它,但我想知道是否有更简单的方法。

标签: pythonvariables

解决方案


要么以空字符串开头并连接,要么以空列表开头并加入。

barfoo = ''
barfoo += 'h'
barfoo += 'i'
print(barfoo)

...

barfoo = []
barfoo.append('h')
barfoo.append('i')
print(''.join(barfoo))

推荐阅读