Python字符串数值
在python开发中对数值和字符串的操作时很常见的,接下来会介绍一些技巧操作。
浮点数精度问题
在涉及金融类计算时,需使用精确计算方法。
def demo1():# 浮点数精度问题print(0.1 + 0.2) # 0.30000000000000004# 使用decimal精确计算res1 = Decimal('0.1') + Decimal('0.2')print(res1) # 0.3
去空格、反转、判断包含
def demo2():# 字符串一些操作a = ' abc 'b = '123'print(a.strip()) # 去除首位空格print(''.join(reversed(b))) # 字符串反转print(a.isdigit()) # 判断字符串是否只包含数字print(b.isdigit())c = 'name:ziwu'# 通过res[-1]拿到最后值,判断是否存在某个符号print(c.partition(':')) # ('name', ':', 'ziwu')print(c.partition('.')) # ('name:ziwu', '', '')
执行结果:

字符串编码、解码
def demo3():a = 'abc'# 将字符串编码为字节串print(a.encode('utf-8')) # b'abc'a_b = a.encode('utf-8')# 字节串解码print(a_b.decode() == a) # True
encode:编码decode:解码
枚举类型使用
class UserType(int, Enum):# VIP 用户VIP = 1# 非VIP用户NO_VIP = 0def demo4(user_type):if user_type == UserType.NO_VIP:print('Hi')elif user_type == UserType.VIP:print('hello, vip')else:print('no type')demo4(user_type=1) # hello, vip
demo4(user_type=0) # Hi
demo4(user_type=2) # no type
本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!
