python中“format”的一些基础使用方法

本文介绍了Python字符串的format方法,该方法可将数据格式化并插入字符串,替换占位符。除默认位置输出外,还有指定顺序、格式化字符串等用法,具体包括位置参数、关键字参数和格式化参数的使用,如关键字参数可指定格式化值,格式化参数能指定插入值格式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

format() 是字符串的一个方法,用于将需要的数据格式化并插入到字符串中。具体而言format() 可以将字符串中的占位符(由一对 {} 组成)替换为指定的值。

除了上文中我们提到的对默认位置的输出,还有包括指定顺序的使用、格式化字符串等使用方式。

位置参数

通俗地讲,我们使用format时,如果在{}中不加内容,那么就是直接按顺序读取format中的内容。在调用 format() 方法时,将需要插入字符串的值作为参数传递给 format() 方法。如果字符串中有多个占位符,可以将多个参数传递给 format() 方法,用逗号隔开。即:

# 位置参数
print('{} is {}'.format('apple', 'fruit'))  # 输出 "apple is fruit"

print('{0} is {1} and {2} is {3}'.format('apple', 'fruit', 'banana', 'not a fruit'))  
# 输出 "apple is fruit and banana is not a fruit"

print('{1} is {0} and {3} is {2}'.format( 'fruit', 'apple', 'not a fruit','banana'))  
# 输出 "apple is fruit and banana is not a fruit"

关键字参数

也可以通过关键字参数来指定要格式化的值。在字符串中使用 {} 占位符,并在其中加上关键字参数名,在调用 format() 方法时,将需要插入字符串的值作为关键字参数传递给 format() 方法。

# 关键字参数
print('{name} is {value}'.format(name='apple', value='fruit'))
# 输出 "apple is fruit"
print('{name} is {value} and {other_name} is {other_value}'.
      format(name='apple', value='fruit', other_name='banana',
             other_value='not a fruit'))  
# 输出 "apple is fruit and banana is not a fruit"

格式化参数

可以使用格式化参数来指定插入值的格式。格式化参数使用 {} 占位符内部的冒号进行指定,并且可以指定一些格式化选项,例如基于浮点数或整数的精度、填充字符和对齐方式等。

# 格式化参数
print('{:.2f}'.format(3.14159))  
# 输出 "3.14"
print('{:0>4d}'.format(42))  
# 输出 "0042"
print('{:0<4d}'.format(42))
# 输出 "4200"
print('{:<10s}{:<10s}'.format('apple', 'fruit'))  
# 输出 "apple     fruit     "
print('{:>10s}{:>10s}'.format('apple', 'fruit'))
# 输出 "     apple     fruit"

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值