Python中星号用法总结

128 阅读1分钟

1、运算符

a = 3 * 2

2、字符串重复

print('#' * 32)

打印时字符串重复32次。

3、函数或方法中的不定长形参

def test(a1,a2, *args, **kwargs):
    代码块

4、星号拆包

def test(a, b, c, d):
    print(a,b,c,d)

list1 = [1, 2, 3, 4]
dict1 = {'a':1, 'b':2, 'c':3, 'd':4}
test(*list1)
test(**dict1)

单星号用于拆解元组和列表,双星号用于拆解字典。

5、源码中使用

在库的源码中经常看到如下代码:

def test(*, a1, a2, a3, a4):
    代码块

其中的星号表示之后的参数必须使用命名参数来传参,调用如下:

test(a1=1, a2=2, a3=3, a4=4)