2

I often find myself doing the following:

a = [1, 3, 2]
b = 'blah blah'
...
print("{} {} {} {}".format(b, a[0], a[1], a[2]))
>blah blah 1 3 2

Is there a way to transform the array into a list of list of parameters? What I mean is the equivalent of:

print("{} {} {} {}".format(b, a))#Not valid Python code
>blah blah 1 3 2

Alternatively, is there a better way of using lists in formatting strings?

Roberto
  • 151
  • 1
  • 5

2 Answers2

1
a = [1, 3, 2]
b = 'blah blah'
print("{} {} {} {}".format(b, *a))

output:

blah blah 1 3 2

Explanation:

{} 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

Refer:

https://www.geeksforgeeks.org/args-kwargs-python/
G1Rao
  • 424
  • 5
  • 11
  • {} 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 – G1Rao Jul 16 '19 at 10:06
  • I've meant to explain it in your answer... You can edit it anytime – FZs Jul 16 '19 at 10:10
0

You can try this:

>>> a = [1,2,3]
>>> b = "str"
>>> print("{} {} {} {}".format(b, a[0], a[1], a[2]))
str 1 2 3
>>> print("{} {} {} {}".format(b, *a))
str 1 2 3

This is related to packing and unpacking in python. Packing and Unpacking

taurus05
  • 2,491
  • 15
  • 28