1、交换变量值
a,b = 2,5
a,b = b,a
2、检查两个字符串是不是由相同字母不同顺序组成
from collections import Counter
Counter(str1) == Counter(str2)
3、链式比较
b = 6
print(4 < b < 7)
4、链式函数调用
def product(a,b):
return a * b
def add(a,b):
return a + b
b = True
print((product if b else add)(3,7))
5、合并字典
d1 = {'a':1}
d2 = {'b':2}
print({**d1,**d2})
print(dict(d1.items()|d2.items()))
6、Python 修改程序的默认时区和工作域的时区
import os,time
os.environ['TZ'] = 'Asia/Shanghai'
time.tzset()
7、Python 判端字符串是否为ip
# 使用Python内置的socket模块来判断字符串是否为IP地址。
# 以下是一个示例代码:
import socket
def is_valid_ip(ip):
try:
socket.inet_aton(ip)
return True
except socket.error:
return False
#使用IPy库来判断一个字符串是否为IPv4地址:
from IPy import IP
def is_valid_ip(ip):
try:
IP(ip)
return True
except ValueError:
return False