NIS*_*ARU 2 python string.format string-formatting args python-3.x
什么是使用*的.format(*)?在下面的格式函数中使用它时,print(new_string.format(*sum_string))它会将输出中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
Run Code Online (Sandbox Code Playgroud)
它与此无关format.*解压缩参数,如果你的列表中有4个占位符和4个元素,那么format解压缩args并填充插槽.例:
args = range(4)
print(("{}_"*4).format(*args))
Run Code Online (Sandbox Code Playgroud)
打印:
0_1_2_3_
Run Code Online (Sandbox Code Playgroud)
在你的第二种情况:
print(new_string.format(*sum_string))
Run Code Online (Sandbox Code Playgroud)
解压参数是字符的字符串(该字符串由参数拆包看作是一个迭代),由于只有一个占位符,只有第一个字符被格式化和打印(和反对的警告,你可以使用C得到编译器和printf,python没有警告你你的参数列表太长,它只是不使用所有这些)
有几个占位符你会看到这个:
>>> args = "abcd"
>>> print("{}_{}_{}_{}").format(*args))
a_b_c_d
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1029 次 |
| 最近记录: |