Python开发——数据类型【字符串格式化】

时间:2023-03-09 01:40:42
Python开发——数据类型【字符串格式化】

字符串格式化之——%

 # 字符串格式化
msg = 'I am %s , My hobby is %s'%('yuan','play')
print(msg) # I am yuan , My hobby is play
#打印浮点数
tpl = "percent %.2f" % 99.976234444444444444
print(tpl) # percent 99.98
#打印百分比
tpl = 'percent %.2f %%' % 99.976234444444444444
print(tpl) # percent 99.98 % tpl = "i am %(name)s age %(age)d" % {"name": "alex", "age": 18}
print(tpl) # i am alex age 18
msg='i am %(name)+60s my hobby is alex' %{'name':'lhf'}
print(msg)
msg='i am \033[43;1m%(name)+60s\033[0m my hobby is alex' %{'name':'lhf'}
print(msg) print('root','x','','',sep=':') # root:x:0:0
# print('root'+':'+'x'+':'+'0','0')

字符串格式化之——format

 # **字典
tpl = "i am {name}, age {age}, really {name}".format(name="seven", age=18)
print(tpl) # i am seven, age 18, really seven
tpl = "i am {name}, age {age}, really {name}".format(**{"name": "seven", "age": 18})
print(tpl) # i am seven, age 18, really seven
# *列表
tpl = "i am {:s}, age {:d}".format(*["seven", 18])
print(tpl) # i am seven, age 18
tpl = "i am {:s}, age {:d}".format("seven", 18) #["seven", 18]
print(tpl) # i am seven, age 18 tpl = "numbers: {:b},{:o},{:d},{:x},{:X}, {:%},{}".format(15, 15, 15, 15, 15, 15.87623, 2)
print(tpl) # numbers: 1111,17,15,f,F, 1587.623000%,2