Python的小技巧和骚操作

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

​

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值