# Python: 你所不知道的星号 * 用法

``````本文大概 1193 个字，阅读需花 6 分钟

``````

``````铃铃铃…… 上课了

呃，星号不就是用来做乘法的嘛，这个还有必要专门列出来吗？

老师这会又在卖关子了？

难道写代码还得强行找理由秀一波星星吗？

这位同学，你太优秀了，先坐下。
平常对于星号的应用场景用得少是不需要了解太多用法的。
不过，学编程的过程少不了要去阅读优秀的源代码库，
也就时常会对星号 * 的贸然出现和用途感到困惑，
所以今天就让你们好好了解一下会有哪些用法，
不要求全记住，略懂一二即可，略懂。。。
``````

## 数值乘法

e.g.

``````mul = 1 * 2
print(mul)
``````

Output:

``````2
``````

## 成员倍增器

e.g.

``````list = ["hello"] * 2
print(list)
``````

Output:

``````["hello", "hello"]
``````

## 幂运算

e.g.

``````print(10 ** 3)
``````

Output:

``````1000
``````

## 函数参数解压操作符

e.g.

``````print(" ".join(["sunday", "monday", "tuesday", "wednesday"]))
print(" ".join("helloworld!"))
``````

Output:

``````sunday monday tuesday wednesday
h e l l o w o r l d !
``````

e.g.

``````print(*"list")
``````

Output:

``````l i s t
``````

e.g.

``````print(*["hello", "world", "!"])
``````

Output:

``````hello world !
``````

## 函数参数修饰符

1. 添加星号 * 在函数的参数前时，表示该参数是不定数量的位置参数。

e.g.

``````def add(*args):
return sum(args)

``````

Output:

``````15
``````
1. 添加两个星号 ** 在函数的参数前时，表示该参数是不定数量的关键字参数。

e.g.

``````def food_type(**kwargs):
for item in kwargs:
print(f"{kwargs[item]} belongs to {item}")

food_type(fruit = "apple", meat = "animal", vegetable = "potato")
``````

Output:

``````apple belongs to fruit
animal belongs to meat
potato belongs to vegetable
``````