带format()的Python默认参数

2024-03-29 06:58:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个关于默认参数值的Python问题:


def command(one="Number 1", a = "{one} .. {two}"):
     two = "Number 2"
     a.format(one=one, two=two)
     return a
print command()

实际输出:{one}。。{2}

期望输出: 1号。。数字2

如果你有什么建议,请告诉我。 谢谢

后续问题:

******你知道吗

import logging
import sys

def command(one="Number 1", a = "{one} .. {two}"):
    two = "Number 2"
    a = a.format(one=one, two=two)           
    logging.error(a)        # Will print
    #logging.debug(a)        # Will not print

command()

为什么日志记录错误会打印,但是日志记录.调试不打印?我认为调试级别低于错误级别,应该打印出来。你知道吗


Tags: importformatnumberreturnloggingdef错误记录
3条回答

线路

    a.format(one=one, two=two)

这就是问题所在。因为str的值是不可变的,所以这一行的结果是解释器按您所期望的方式格式化,但它不会将值赋回a(字符串是不可变的)。你知道吗

所以当你

    return a

您的a仍然是以前未格式化的a。你知道吗

解决办法是把这两条线结合起来

    return a.format(one=one, two=two)

针对后续问题:

logging.debug(whatever)可能不会显示,因为logging可能尚未配置为显示DEBUG级别。要更正此问题,请使用basicConfig函数:

import logging
logging.basicConfig(level=logging.DEBUG)

str.format不会修改字符串。它只返回基于其参数的新修改的字符串。所以你真正想要的是这样的:

def command(one="Number 1", a = "{one} .. {two}"):
     two = "Number 2"
     return a.format(one=one, two=two)

print command()

在Python中,strstring函数都没有实际修改它们处理的字符串,而是倾向于返回新字符串。这是因为字符串是不可变的,即它们不能被修改。你知道吗

您需要将a重新分配给a = a.format(one=one, two=two),或者只返回它。你知道吗

return a.format(one=one, two=two)

a.format不会更改原始字符串a,字符串是不可变的,因此a.format所做的就是创建一个新字符串。任何时候修改一个字符串都会创建一个新对象。除非使用连接,否则要更改a的值,需要将a重新分配给新对象。你知道吗

str.replace是人们被抓的另一个例子:

In [4]: a = "foobar"

In [5]: id(a)
Out[5]: 140030900696000
In [6]: id(a.replace("f","")) # new object
Out[6]: 140030901037120
In [7]: a = "foobar"     
In [8]: a.replace("f","")
Out[8]: 'oobar'
In [9]: a  # a still the same
Out[9]: 'foobar'
In [10]: id(a)
Out[10]: 140030900696000
In [11]: a = a.replace("f","") # reassign a 
In [12]: id(a) 
Out[12]: 140030900732000    
In [13]: a 
Out[13]: 'oobar'

相关问题 更多 >