字符串格式化
# 字符串格式化
tpl = "I am {name}, age {age}, really {name}".format(name="seven", age=18)
# 字符串格式化,使用字典时要带上**
tpl = "I am {name}, age {age}, really {name}".format(**{"name": "seven", "age": 18})
# 字符串格式化,使用列表时要带上*,{:s}表示接收字符串,{:d}表示接收整型
tpl = "I am {:s}, age {:d}".format(*["seven", 18])
tpl = "I am {:s}, age {:d}".format("seven", 18)
# 字符串格式化,使用自定义列表(常用)
l = ["seven", 18]
tpl = "I am {:s}, age {:d}".format(*l)
print(tpl)
# 字符串格式化
tpl = "I am %(name)s age %(age)d" % {"name": "alex", "age": 18}
print(tpl)
# 字符串格式化,{:b}表示接收二进制,{:o}表示接收八进制,{:d}表示接收十进制,{:x}{:X}分别表示接收十六进制小写和大写,{:%}表示接收百分比
tpl = "numbers: {:b},{:o},{:d},{:x},{:X}, {:%},{}".format(15, 15, 15, 15, 15, 15.87623, 2)
print(tpl)
函数定义
def test(x, *args, **kwargs):
print('x:', x)
print('args:', args, 'args[-1]', args[-1])
print('kwargs:', kwargs, 'kwargs.gety', kwargs.get('y'))
# test(1,1,2,1,1,11,1,x=1,y=2,z=3) #报错
test(1, 1, 2, 1, 1, 11, 1, y=2, z=3)
test(1, *[1, 2, 3], **{'y': 1})
得到输出结果:
x: 1
args: (1, 2, 1, 1, 11, 1) args[-1] 1
kwargs: {'y': 2, 'z': 3} kwargs.gety 2
x: 1
args: (1, 2, 3) args[-1] 3
kwargs: {'y': 1} kwargs.gety 1
set常用方法
# pop 随机删除一个元素(集合没有顺序)
s = {'sb', 1, 2, 3, 4, 5, 6}
s.pop()
# remove discard 指定删除
s.remove('sb')
# s.remove('hellol') # 删除元素不存在则会报错
s.discard('sbbbb') # 删除元素不存在不会报错
print(s)
python_l=['lcg','szw','zjw','lcg']
linux_l=['lcg','szw','sb']
p_s=set(python_l)
l_s=set(linux_l)
# intersection 求交集,相当于&运算符
print(p_s,l_s)
print(p_s.intersection(l_s))
print(p_s&l_s)
# union 求并集,相当于|运算符
print(p_s.union(l_s))
print(p_s|l_s)
# difference 求差集,相当于-运算符,注意顺序有影响
print('差集',p_s-l_s)
print(p_s.difference(l_s))
print('差集',l_s-p_s)
print(l_s.difference(p_s))
# symmetric_difference 交叉补集
print('交叉补集',p_s.symmetric_difference(l_s))
print('交叉补集',p_s^l_s)
# difference_update 求差集并更新
p_s.difference_update(l_s)
print(p_s)
# isdisjoint 如果两集合没有交际则返回True
s1={1,2}
s2={2,3,5}
print(s1.isdisjoint(s2))
# issubset 判断是否子集,注意顺序有影响
s1 = {1, 2}
s2 = {1, 2, 3}
print(s1.issubset(s2)) # s1 是s2 的子集
print(s2.issubset(s1)) # False
# issuperset 判断是否父集,注意顺序有影响
print(s2.issuperset(s1)) # s1 是s2 的父集
# frozenset 创建不可更改集合
s = frozenset('hello')
print(s)
names = ['alex', 'alex', 'wupeiqi']
names = list(set(names))
print(names)
# sep创建间隔符
print('root','x','0','0',sep=':')