Python字符串格式化

字符串格式化用来把整数、实数等对象转化为特定格式的字符串


1. % 格式字符

% 格式字符:% 之前的字符串为格式字符串,之后的部分为需要格式化的内容

例如:

name = "cspsy"
job = "student"
print("My name is %s." % name)
# 如果有多个需要进行格式化的内容,需要使用 () 将其包裹。
print("My name is %s and my job is %s." % (name, job))

在这里插入图片描述

1.1)常见的格式字符

在这里插入图片描述


2. format()

format().format() 之前的字符串为格式字符串,里面的部分的内容为需要格式化的内容
格式串中的 {} 的内容与 format() 里面的内容相对应。

format() 方法进行格式化:

  • 可以使用位置进行格式化
  • 可以使用自定义的参数名字进行格式化
  • 支持序列解包来进行格式化

2.1)使用位置

  • 不写位置下标,则格式字符串内的花括号带的下标默认从 0 开始递增排列
name = "cspsy"
job = "student"
print("My name is {} and my job is {}.".format(name, job))

在这里插入图片描述

  • 书写位置下标,输出括号内指定位置下标的内容(括号内下标从 0 开始递增排列
one, two, three = 1, 2, 3
print("You use {0}, {2}, {1}.".format(one, two, three))

在这里插入图片描述

2.2)使用自定义的参数名字

  • 可以在格式字符串的 {} 内使用自定义的参数名字,与待格式化的内容对应。
    例如:
one, two, three = 1, 2, 3
print("You use {o}, {thr}, {tw}.".format(o=one, tw=two, thr=three))

在这里插入图片描述

2.3)使用序列解包

将解包后的名字,key 值放在格式化字符串内。
例如:

number = {'one': 1, 'two': 2, 'three': 3}
print("You use {one}, {three}, {two}.".format(**number))

在这里插入图片描述

2.4)格式风格

  • 数字

进制转换

one, two, three = 11111, 2222, 3
print("You use {0:#x}, {1:#o}, {2:#b}".format(one, two, three))

在这里插入图片描述

保留小数点
使用 :.xfx 为想要保留的小数点个数,如果 : 后面带有 +,则会保留符号输出。

one, two, three = 11111.1111, 2.2222, 3.3333333
print("You use {0:.2f}, {1:+.0f}, {2:.3f}".format(one, two, three))

在这里插入图片描述

科学计数法

one, two, three = 11111.1111, 2.2222, 3.3333333
print("You use {0:.2e}, {1:+.0e}, {2:.3e}".format(one, two, three))

在这里插入图片描述
百分比形式

one, two, three = 11111.1111, 2.2222, 3.3333333
print("You use {0:.0%}, {1:.2%}, {2:.3%}".format(one, two, three))

在这里插入图片描述

以逗号分隔

one, two, three = 11111.1111, 2.2222, 3.3333333
print("You use {0:,}, {1:,}, {2:,}".format(one, two, three))

在这里插入图片描述

  • 对齐方式

使用 :cxn 来进行,n 为最小长度,c 为长度不够时,填充的字符(不写则为空格)
x 为对齐方式:其中,^:居中,<:左对齐,>:右对齐

例如:

one, two, three = 11111.1111, 2.2222, 3.3333333
print("You use {0:#^12.2f}, {1:.<+8.0f}, {2:>7.3f}".format(one, two, three))

在这里插入图片描述


3. map

可以通过内置 map() 函数来进行格式化字符串输出:

formatter = "You use {0}".format
for num in map(formatter, range(1, 6)):
    print(num)

在这里插入图片描述
这个例子写法与下面等价:

formatter = "You use {0}".format
for num in range(1, 6):
    print(formatter(num))

4. f-字符串

从 Python 3.6.x 开始支持一种新的字符串格式化方式,官方叫做 Formatted String Literals,简称 f-字符串,在字符串前加字母 f,在 {}填写表达式
使用如下:

one, two, three = 11, 222, 3333
print(f'You use {one}, {two * three}.')

在这里插入图片描述
Python 3.8 之后,还可以 {xxx=},将 xxx=输出出来且输出它对应的值:

one, two, three = 1, 2, 3
print(f'You use {one}, {two * three}, {two * three = }.')

在这里插入图片描述

  • 7
    点赞
  • 29
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值