python字符串格式化

本文介绍了Python中两种字符串格式化的方法:百分号方式和format方式。包括基本用法、字符串截取、浮点数保留位数等操作,并通过多个示例进行说明。

Python的字符串格式化有两种方式: 百分号方式、format方式

%方法

# %[(name)][flags][width].[precision]typecode
# %s 后面跟时 直接加%后面 如果是s就跟任意类型,d就跟整型
健身房的
tel = "i am %s hello world "%'lucky'
print(tel)
print("i am %s my age is %d"%('lucky', 20))
print('i am %(name)s my age is %(age)d '%{'name':'lucky', 'age': 20})

#   字符串截取
print('i am %.3s'%'abcderg') # 只有三位字符

#   浮点数
print('i am precent %.2f'%1.234)
print('i am %(pp).2f'%{'pp': 1.2345})
#   保留两位小数
a = '%.2f'%12.3
print(a)
# tpl = "i am %.2f %%" % {"pp": 123.425556, }
# print(tpl)

format方法

tpl = "i am {}, age {}, {}".format("seven", 18, 'alex')
  
tpl = "i am {}, age {}, {}".format(*["seven", 18, 'alex'])
  
tpl = "i am {0}, age {1}, really {0}".format("seven", 18)
  
tpl = "i am {0}, age {1}, really {0}".format(*["seven", 18])
  
tpl = "i am {name}, age {age}, really {name}".format(name="seven", age=18)
  
tpl = "i am {name}, age {age}, really {name}".format(**{"name": "seven", "age": 18})
  
tpl = "i am {0[0]}, age {0[1]}, really {0[2]}".format([1, 2, 3], [11, 22, 33])
  
tpl = "i am {:s}, age {:d}, money {:f}".format("seven", 18, 88888.1)
  
tpl = "i am {:s}, age {:d}".format(*["seven", 18])
  
tpl = "i am {name:s}, age {age:d}".format(name="seven", age=18)
  
tpl = "i am {name:s}, age {age:d}".format(**{"name": "seven", "age": 18})
 
tpl = "numbers: {:b},{:o},{:d},{:x},{:X}, {:%}".format(15, 15, 15, 15, 15, 15.87623, 2)
 
tpl = "numbers: {:b},{:o},{:d},{:x},{:X}, {:%}".format(15, 15, 15, 15, 15, 15.87623, 2)
 
tpl = "numbers: {0:b},{0:o},{0:d},{0:x},{0:X}, {0:%}".format(15)
 
tpl = "numbers: {num:b},{num:o},{num:d},{num:x},{num:X}, {num:%}".format(num=15)

 

转载于:https://www.cnblogs.com/xiaokang01/p/9021777.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值