无法将函数的 return 写入文件
Not able to write an return of a function to file
谁能解释一下为什么我不能这样做,是否有任何解决方法?
这适用于 ex.
a, b, c, d = extract(text)
fw.write("Number of SMS: {0} \nCharacters before extraction: {1} \nCharacter after extraction: {2} \nOverhead: {3:.0f}%".format(a, b, c, d))
但这并不
fw.write("Number of SMS: {0} \nCharacters before extraction: {1} \nCharacter after extraction: {2} \nOverhead: {3:.0f}%".format(extract(text)))
如果 extract()
return 是一个元组,您需要在将 return 值传递给格式之前将其解压缩:
.format(*extract(text))
星号在这里起到了作用。
说明: in Python,string#format
具有以下签名:
.format(*args, **keyword_args)
*
和 **
被称为解包操作符(在 Ruby 中,它们被称为 splats)。它们的唯一目的是分别将列表(元组、数组)和字典(字典、对象)转换为参数列表。
extract()
return 是一个列表,但格式需要一个参数列表。所以之前,你有:
#if the output of extract(text) is ('foo', 'bar') or ['foo', 'bar']
.format(extract(text)) # this thing
.format(('foo', 'bar')) # is equivalent to this, note the parentheses
在这种情况下,元组 ('foo', 'bar') 等于第一个格式标记 {0}
,格式不知道如何处理元组标记(我应该使用元组的哪些元素?)。
当您使用扩展运算符时,您正在将 extract()
的输出转换为函数期望的列表,因此:
#if the output of extract(text) is ('foo', 'bar') or ['foo', 'bar']
.format(*extract(text)) # this thing
.format('foo', 'bar') # is equivalent to this
谁能解释一下为什么我不能这样做,是否有任何解决方法?
这适用于 ex.
a, b, c, d = extract(text)
fw.write("Number of SMS: {0} \nCharacters before extraction: {1} \nCharacter after extraction: {2} \nOverhead: {3:.0f}%".format(a, b, c, d))
但这并不
fw.write("Number of SMS: {0} \nCharacters before extraction: {1} \nCharacter after extraction: {2} \nOverhead: {3:.0f}%".format(extract(text)))
如果 extract()
return 是一个元组,您需要在将 return 值传递给格式之前将其解压缩:
.format(*extract(text))
星号在这里起到了作用。
说明: in Python,string#format
具有以下签名:
.format(*args, **keyword_args)
*
和 **
被称为解包操作符(在 Ruby 中,它们被称为 splats)。它们的唯一目的是分别将列表(元组、数组)和字典(字典、对象)转换为参数列表。
extract()
return 是一个列表,但格式需要一个参数列表。所以之前,你有:
#if the output of extract(text) is ('foo', 'bar') or ['foo', 'bar']
.format(extract(text)) # this thing
.format(('foo', 'bar')) # is equivalent to this, note the parentheses
在这种情况下,元组 ('foo', 'bar') 等于第一个格式标记 {0}
,格式不知道如何处理元组标记(我应该使用元组的哪些元素?)。
当您使用扩展运算符时,您正在将 extract()
的输出转换为函数期望的列表,因此:
#if the output of extract(text) is ('foo', 'bar') or ['foo', 'bar']
.format(*extract(text)) # this thing
.format('foo', 'bar') # is equivalent to this