问题描述
.format(*)中*的用途是什么?
在print(new_string.format(*sum_string))下面的format函数中使用它时,它将输出中sum_string的值从18更改为1为什么会发生这种情况?
我已经阅读了有关*args和**kwargs的以下链接,但无法理解该链接如何应用于.format()函数
sum_string = "18"
new_string = "This is a new string of value {}"
print(new_string.format(sum_string)) #it provides an output of value 18
print(new_string.format(*sum_string)) #it provides an output of value 1
1楼
与format无关。
*解压缩的参数,所以如果有,说4个占位符,并在列表中4个元素,然后format解包指定参数和填充插槽。
例:
args = range(4)
print(("{}_"*4).format(*args))
打印:
0_1_2_3_
在第二种情况下:
print(new_string.format(*sum_string))
解压参数是字符串(该字符串由参数拆包看作是一个迭代)的特点 ,而且由于只有一个占位符,只有第一个字符被格式化和打印(和反对的警告,你可以使用C得到编译器和printf ,python不会警告您参数列表过长,只是不使用所有参数)
使用几个占位符,您会看到:
>>> args = "abcd"
>>> print("{}_{}_{}_{}").format(*args))
a_b_c_d