我经常发现自己在做以下事情:
a = [1, 3, 2]
b = 'blah blah'
...
print("{} {} {} {}".format(b, a[0], a[1], a[2]))
>blah blah 1 3 2
有没有一种方法可以将数组转换为参数列表?我的意思是等同于:
print("{} {} {} {}".format(b, a))#Not valid Python code
>blah blah 1 3 2
或者,在格式化字符串时,有没有更好的方法使用列表?
答案 0 :(得分:1)
a = [1, 3, 2]
b = 'blah blah'
print("{} {} {} {}".format(b, *a))
输出:
blah blah 1 3 2
说明:
{} is called placeholder, *a is a variable length argument,
when you are not sure about the number of arguments in a function,
there you can use a variable length argument(*a), in the above format
function takes two arguments, one is b, second one is (variable length) a,
the place holder will be filled based on input, first one is filled by b,
2nd, 3rd....... filled by a
引用:
https://www.geeksforgeeks.org/args-kwargs-python/
答案 1 :(得分:0)