Python字符串处理
1. 格式化字符串
%格式化
最早用%
进行格式化字符串
# %d %s %f 格式化字符串
name = "Max"
num = 1
print("Hello %s, your num is %d"%(name, num)) # Hello Max, your num is 1
# 也支持字典形式格式化
print("Hello[%(name)s], your num is %(num)d"%{"num":1, "name":"Max"})
str.format格式化
占位符{}
# 1.常规用法
name = "max"
print("your name is {}".format(name))
# 2.通过位置访问
age = 1
print("Hello {1}, your age is {0}".format(age, name))
# 3.通过关键词访问
print("Hello {name}".format(name="Max"))
f-string格式化
格式化字符串常量
name = "max"
print(f'Hello {name}') # Hello max
print(f'Hello {name.upper()}') # Hello MAX
d = {'id':1, 'name': 'Max'}
print(f'Name[{d["id"]}]: {d["name"]}') # Name[1]: Max
2. 字符串补0
python 字符串补全填充固定长度(补0)的三种方法
# 原字符串左侧对齐, 右侧补零:
str.ljust(width,'0')
input: '789'.ljust(32,'0')
output: '78900000000000000000000000000000'
'''python
原字符串右侧对齐, 左侧补零:
方法一:
'''
str.rjust(width,'0')
input: '798'.rjust(32,'0')
output: '00000000000000000000000000000798'
'''
方法二:
'''python
str.zfill(width)
input: '123'.zfill(32)
output:'00000000000000000000000000000123'
'''
方法三:
'''python
'%07d' % n
input: '%032d' % 89
output:'00000000000000000000000000000089'