python字符串格式化指南
在 Python 中,字符串格式化是一种常见且重要的操作,用于将变量或值插入到字符串中,并控制输出的格式。本文将介绍几种常见的字符串格式化方法,帮助大家掌握在 Python 中有效地处理字符串的技巧。
1,使用"%"操作符实现字符串格式化
使用%操作符是早期的python提供的方法,语法:str%data
常用的格式化字符串
- - %s 字符串 (采用str()的显示)
- - %r 字符串 (采用repr()的显示)
- - %f (%F) 浮点数,
- - %d 十进制整数
- - %c 单个字符
- - %b 二进制整数
- - %i 十进制整数
- - %o 八进制整数
- - %x 十六进制整数
- - %e(%E) 指数 (基底写为e)
- - %g (%G)指数(e)或浮点数 (根据显示长度)
- - %% 字符"%"本身,显示百分号%
> name = "lily"
> age = 25
> weight=54.7
> print("My name is %s and I'm %d years old and my weight is %.1f kg." % (name, age,weight))
My name is lily and I'm 25 years old and my weight is 54.7 kg.
特殊的数字及浮点数需求
正常我们输出一个十进制整数的时候,直接使用%d就足以,这种正常打印数字肯定没有问题,但是在生活中,如果需要打印工号、学号等等有00开头的数字,如果再使用这种格式化字符串打印的话,肯定就难以实现。这里引入"%03d",其中数字3可以更改为其他数字。该字符串格式化代表的意思是控制台输出几位数字
> number1 = 26
> print("This number is %03d" % number1)
This number is 026
> age1 = 888
> print("This number is %03d" % age1)
This number is 888
> print("This number is %06d" % number1)
#This number is 000026
> weight = 64.5
> print("His weight is %.f kg." % weight)
His weight is 64 kg.
> print("His weight is %.1f kg." % weight)
His weight is 64.5 kg.
> print("His weight is %.2f kg." % weight)
His weight is 64.50
2,使用format方法对字符串进行格式化
自python2.6版本开始,python提供了format方法、语法如下:str.format(data)
#位置参数
>> '{0} love {1}.{2}'.format('I','love','python')
'I love python'
#当值为关键字参数时,举例说明
>> '{a} love {b}.{c}'.format(a = 'I',b = 'love',c = 'python')
'I love python'
#当然,也支持两种混用,format()内的无赋值的参数必须放左边,举例说明
>> '{0} love {b}.{c}'.format('I',b = 'FishC',c = 'com')
'I love python'
#如果字符串中没有定义替换部分,则返回原字符串
>>> '我不需要被替换'.format('不打印')
'我不需要被替换'
>>> '我不需要被替换'.format()
'我不需要被替换'
#注意,在字符串中花括号表示其内的内容是要被替换的,如果想让花括号和其内的内容是作为一个正常字符串处理的话,必须在外面再加一层花括号,
#这种形式类似转义字符前面加上转义字符表示其本身一样,举例说明
'{{0}}'.format('不打印')
'{0}'
#最后,位置参数直接跟':'表明后面跟一个字符串格式化操作符,举例说明
>>> '{0:.1f}{1}'.format(27.68,'GB') #.1f表明是格式化小点数且保留小数点后1位
'27.7GB
使用 f-strings
自从 Python 3.6 版本开始,引入了 f-strings,它是一种直观且易用的字符串格式化方法,可以在字符串前加上 f 或 F 来创建格式化字符串,强烈建议优先使用这个方法。
> a='python'
> f'I Love {a}'
'I Love python'
#可以接收表达式
> num=12
> price=6
> print(f'【{num}】个苹果,每个【peice】元,一共要花费【{num*price}】元')
【{12}】个苹果,每个【6】元,一共要花费【{72}】元
#可以对字典取值
> user={'name':'ace','job':'tracher'}
> print('【{user['name']}】的工作是【{user['job']}】')
【ace】的工作是【teacher】
#对多行数据进行格式化
> name='李四'
> age=28
> job='码农'
> msg=(
f'name:{name}\n'
f'age:{age}\n'
f'job:{job}'
)
> print(msg)
name:李四
age: 28
job:码农
#调用函数
def my_max(x,y):
return x if x>y else y
> a,b=3,4
> print(f'【{a}】和【{b}】中比较大的是【{my_max(a,b)}】')
【{3}】和【{4}】中比较大的是【4】
#格式化浮点数
val=11.57
print(f'{val:.3f}')
11.570
print(f'{val:.1f}')
11.5
#接收一个对象,注意:对象必须定义了__str__()或__repr__()函数
class User:
def __init__(self,name,job):
self.name=name
self.job=job
def __repr__(self):
return f'{self.name} is a {self.job}'
> u=User('Ace','teacher')
> print(f'{u}')
Ace is teacher
本文介绍了在 Python 中常用的字符串格式化方法,包括 % 操作符、tr.format() 方法和 f-strings。这些方法都可以帮助我们根据需要将变量插入到字符串中,并控制输出的格式。根据实际情况和个人偏好,选择合适的字符串格式化方法,以提高代码的可读性和灵活性