str.format() method

本文详细介绍了Python中字符串格式化的多种方法,包括使用加号连接、str.format()方法的不同用法,如按顺序插入变量、指定顺序重复变量及通过关键字参数传递值进行格式化。

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

字符串输出

name = "Kylie"
num = 8
output = name + "'s favorite number is " + str(num)
print(output)

Kylie’s favorite number is 8

str.format() method 输出

1. The variables are inserted into the {} by the order that we pass them as arguments.
output = "{}'s favorite number is {}".format("Kylie", 8)
print(output)

Kylie’s favorite number is 8

2. Use integer to specify ordering and/or repeat numbers
output = "{0}'s favorite number is {1}, {1} is {0}'s favorite number".format("Kylie", 8)
print(output)

Kylie’s favorite number is 8, 8 is Kylie’s favorite number

3. Use keyword arguments to pass values to str.format()
template = "{name}'s favorite number is {num}, {num} is {name}'s favorite number"
output = template.format(name="Kylie", num="8")
print(output)
` ``
Kylie's favorite number is 8, 8 is Kylie's favorite number
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值