How does an asterisk `*` work in the string formatting method `.format(*) ` in Python 3?

天涯浪子 提交于 2019-12-11 03:19:21

问题


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

回答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


来源:https://stackoverflow.com/questions/52475322/how-does-an-asterisk-work-in-the-string-formatting-method-format-in-p

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!