python字符串格式化

1、% 格式化

name = 'xiaoming'
age = '10'

test = '%s is %s years old' % (name, age)
print(test)

xiaoqing is 10 years old

% 也支持字典形式的传递,如下:

test1 = 'Hello %(name)s,id=%(id)s' % {'id': 10, 'name': 'World'}
print(test1)

Hello World,id=10
  • 格式化符号

%s:字符串

%d:十进制整数

%f:浮点数,可指定小数点后的精度

%e:用科学计数法格式化浮点数

%%:字符"%",显示百分号%

  • 格式控制

%[(name)][flags][width].[precision] typecode

flags
-:用做左对齐(默认右对齐)
+:在正数前面显示加号( + )
0:显示的数字前面填充’0’而不是默认的空格

如:

%-5d    #左对齐,宽度5,不足右边默认补空格
%05d    #右对齐,不足左边补0
%f      #默认是输出6位有效数据,会进行四舍五入  
%.2f    #保留小数点后2位

2、str.format()

常规用法
通过 {} 和 : 来代替以前的 %,:用于格式控制

name = 'xiaoming'
age = '10'

test2 = 'hello, {}, you are {}?'.format(name, age)
print(test2)

hello, xiaoming, you are 10?

通过位置访问

name = 'xiaoming'
age = '10'

test2 = 'hello, {0}, you are {1}?'.format(name, age)
print(test2)

hello, xiaoming, you are 10?

通过关键字访问

name = 'xiaoming'
age = '10'

test3 = 'hello, {name}, you are {age}?'.format(name=name, age=age)
print(test3)

hello, xiaoming, you are 10?
  • 格式控制

^, <, > 分别是居中、左对齐、右对齐,后面带宽度 : 号后面带填充的字符,只能是一个字符,不指定则默认是用空格填充

+表示在正数前显示 +,负数前显示 -, 空格表示在正数前加空格

b、d、o、x 分别是二进制、十进制、八进制、十六进制

使用大括号 {}来转义大括号

如:

{:+.2f}    #带符号保留小数点后两位
{:0>2d}    #数字补零 (填充左边, 宽度为2)

3、f 格式化

f 格式化是 python3.6 之后版本添加的,称之为字面量格式化字符串,是新的格式化字符串的语法。用了这种方式明显更简单了,不用再去判断使用 %s,还是 %d。

name = 'xiaoming'
age = '10'

test4 = f'hi, {name}, are you {age}?'
print(test4)

hi, xiaoming, are you 10?

在 Python 3.8 的版本中可以使用 = 符号来拼接运算表达式与结果:

x = 1
print(f'{x+1=}')

x+1=2
  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值