What is the use of *
in .format(*)
?
When using it in the format function below print(new_string.format(*sum_string))
it changes the value of sum_string in the output from 18 to 1
Why does that happen?
I have read the following link about *args
and **kwargs
but couldn't understand how does that apply to the .format()
function
What does ** (double star/asterisk) and * (star/asterisk) do for parameters?
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
it has nothing to do with format
. *
unpacks the arguments so if there are, say 4 placeholders and 4 elements in your list, then format
unpacks the args and fills the slots. Example:
args = range(4)
print(("{}_"*4).format(*args))
prints:
0_1_2_3_
In your second case:
print(new_string.format(*sum_string))
the arguments to unpack are the characters of the string (the string is seen as an iterable by the argument unpacking), and since there's only one placeholder, only the first character is formatted & printed (and as opposed to warnings you could get with C compilers and printf
, python doesn't warn you about your list of arguments being too long, it just doesn't use all of them)
With several placeholders you'd witness this:
>>> args = "abcd"
>>> print("{}_{}_{}_{}").format(*args))
a_b_c_d