【问题标题】:str.format() option is not workingstr.format() 选项不起作用
【发布时间】:2013-12-22 04:00:29
【问题描述】:

此代码取自教程:

def main():
    stri = "Hello, {person}"
    stri.format(person="James")
    print(stri) #prints "Hello, {person}"

为什么format() 不起作用?

【问题讨论】:

    标签: python string format


    【解决方案1】:

    确实有效。您只是没有将格式分配给变量,然后只是打印原始字符串。请参见下面的示例:

    >>> s = 'hello, {person}'
    >>> s
    'hello, {person}'
    >>> s.format(person='james')
    'hello, james'                    # your format works
    >>> print s                       # but you did not assign it
    hello, {person}                   # original `s`
    >>> x = s.format(person='james')  # now assign it
    >>> print x 
    hello, james                      # works!
    

    【讨论】:

    • 为什么要在每行的开头输入“>>>”?
    • @Netherwire 它暗示这是输入。没有它的行被输出
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-08
    • 1970-01-01
    • 2010-12-09
    相关资源
    最近更新 更多