格式为()的Python默认参数
我有一个关于默认参数值的Python问题:格式为()的Python默认参数,python,Python,我有一个关于默认参数值的Python问题: 实际输出:{1}。。{two} 期望输出: 第一。。二号 如果你有任何建议,请告诉我。 谢谢 后续问题: ****** 为什么logging.error会打印,而logging.debug不会打印?我认为调试级别低于错误级别,应该打印出来。行 a.format(one=one, two=two) 这就是问题所在。由于strings是不可变的,因此在这一行上发生的是解释器按照您期望的方式格式化,但它不会将值赋回a(字符串是不可变的) 所以
实际输出:{1}。。{two} 期望输出: 第一。。二号 如果你有任何建议,请告诉我。 谢谢 后续问题: ******
为什么logging.error会打印,而logging.debug不会打印?我认为调试级别低于错误级别,应该打印出来。行
a.format(one=one, two=two)
这就是问题所在。由于str
ings是不可变的,因此在这一行上发生的是解释器按照您期望的方式格式化,但它不会将值赋回a
(字符串是不可变的)
所以当你
return a
您的a
仍然是以前未格式化的a
解决办法是将这两条线合并为一条线
return a.format(one=one, two=two)
针对后续问题:
logging.debug(无论什么)
可能不会显示,因为logging
可能未配置为显示debug
级别。要更正此问题,请使用basicConfig
功能:
import logging
logging.basicConfig(level=logging.DEBUG)
您需要将
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'
str.format
不会修改字符串。它仅返回基于其参数的新修改字符串。所以你真正想要的是这样的:
def command(one="Number 1", a = "{one} .. {two}"):
two = "Number 2"
return a.format(one=one, two=two)
print command()
在Python中,
str
和string
函数实际上都没有修改它们处理的字符串,而是倾向于返回新字符串。这是因为字符串是不可变的,即它们不能修改。非常感谢,请参阅后续问题。检查编辑以获取后续问题的解决方案
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'
def command(one="Number 1", a = "{one} .. {two}"):
two = "Number 2"
return a.format(one=one, two=two)
print command()