Python字符串格式化
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python字符串格式化相关的知识,希望对你有一定的参考价值。
1.1.1 字符串的格式化
>>> ‘hello,%s‘ % ‘world‘ --字符串替换
‘hello,world‘
>>> ‘Hi,%s,you salary is $%d‘ %(‘DAIDAI‘,100000) --字符串替换&整数替换
‘Hi,DAIDAI,you salary is $100000‘
1.1.1.1 整数的格式化
%d
>>> a=7
>>> ‘%14d abc‘ % a --表示留空14个占位符
‘ 7 abc‘
>>> ‘%04d abc‘ % a --表示留空4个占位符,用0代替
‘0007 abc‘
1.1.1.2 浮点数的格式化
%f
>>> PI=3.141516
>>> ‘%.3f abc‘ % PI --保留小数点后3位,你发现已四舍五入
‘3.142 abc‘
1.1.1.3 字符串的格式化
%s
>>> ‘char: %s,number: %s‘ %(‘DAIDAI‘,‘12310‘)
‘char: DAIDAI,number: 12310‘
>>> ‘char: %s,number: %s‘ %(‘DAIDAI‘,12310)
‘char: DAIDAI,number: 12310‘
如果你不太确定应该用什么,%s永远起作用,它会把任何数据类型转换为字符串
有些时候,字符串里面的%是一个普通字符怎么办?这个时候就需要转义,用%%来表示一个%
>>> ‘percentage:%d%%‘ % 45
‘percentage:45%‘
本文出自 “90SirDB” 博客,请务必保留此出处http://90sirdb.blog.51cto.com/8713279/1795430
以上是关于Python字符串格式化的主要内容,如果未能解决你的问题,请参考以下文章