【问题标题】:Adding values inside function to an empty string outside of a function将函数内部的值添加到函数外部的空字符串
【发布时间】:2012-09-24 21:17:14
【问题描述】:
empty_string = ''
string_1 = 'beta'

def sample(x):
    empty_string = empty_string + 'alpha'
    return x

为什么不:

empty_string = 'alpha'

我很困惑为什么在函数中添加empty_string 后仍然为空

【问题讨论】:

  • @Ashwini 的回答很好,但是,通常最好让字符串函数返回一个新字符串,并且调用者可以根据需要更新变量。所以def alphaize(s): return s + 'alpha'然后在函数之外empty_string = alphaize('foo')

标签: python string function concatenation


【解决方案1】:

在函数内部使用global empty_string,那么只有你可以修改一个全局变量:

def sample(x):
    global empty_string
    empty_string = empty_string + 'alpha'
    return x

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-12-15
    • 1970-01-01
    • 1970-01-01
    • 2013-09-13
    • 2012-08-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多