Python字符串操作

设置字符串格式

这里的基本思想是对字符串调用方法format()并提供设置其格式的的值。

注意用{}括起来的字符串

替换字段名


#最简单情况,一一对应代换
>>> "{},{},{},{}".format(1,3,4,6)
'1,3,4,6'

 

>>> "{foo},{}{fab}".format(5,foo=6,fab=10)
'6,510'
'''注意:在“”中只有{foo}与{}之间有“,”所以输出时只有一个“,”'''
fullname=["Alice","Sto"]
print("abc,{nmae[1]}".format(nmae=fullname))

输出:abc,Sto

 

基本转换

str="The number is {num}.".format(num=42)
print(str)
str="The number is {num:f}".format(num=42)#{num:f}表示num为实型
print(str)
str="The number is {num:b}".format(num=42)#num二进制输出
print(str)
str="The number is {num:e}".format(num=42.0543)#科学表示法
print(str)
#E与e相同
#%将数表示成百分数
#。。。
输出:
The number is 42.
The number is 42.000000
The number is 101010
The number is 4.205430e+01

 

宽度:

str="{num:10}".format(num=3)#设置宽度为10
print("'"+str+"'")
str="{num:10}".format(num="Bob")
print("'"+str+"'")

输出:

'         3'
'Bob       '

 精度:

import math
Str="{pi:5.2f}".format(pi=math.pi)
print(Str)

输出:

3.14(宽度为5)

不仅可以对数值制定精确度,其他类型也可以,只是不常见

str="{:.5}".format("123456789")
print(str)

 输出:

12345

符号、对齐和用0填充

import math
str="'{:010.2f}'".format(math.pi)
print(str)

输出:

'0000003.14'

对其方式:

要指定左对齐、右对齐、和居中用<、>和^

import math
print("'{0:<10.2f}'".format(math.pi))
print("'{0:>10.2f}'".format(math.pi))
print("'{0:^10.2f}'".format(math.pi))

输出:

'3.14      '
'      3.14'
'   3.14   '
print("'{:#^10.2f}'".format(math.pi))

输出:

'###3.14###'
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值