字符串格式化-format用法

基本用法

最基本的用法是通过花括号 {} 占位符来插入变量。

name = "Alice"
age = 30
formatted_string = "My name is {} and I am {} years old.".format(name, age)
print(formatted_string)

输出:

My name is Alice and I am 30 years old.

指定位置

你可以通过在花括号中指定位置索引来确定插入的顺序。

formatted_string = "My name is {0} and I am {1} years old. {0} loves programming.".format(name, age)
print(formatted_string)

输出:

My name is Alice and I am 30 years old. Alice loves programming.

使用命名参数

可以使用命名参数,使代码更加清晰。

formatted_string = "My name is {name} and I am {age} years old.".format(name="Alice", age=30)
print(formatted_string)

输出:

My name is Alice and I am 30 years old.

混合位置参数和命名参数

可以混合使用位置参数和命名参数,但所有位置参数必须出现在命名参数之前。

formatted_string = "My name is {} and I am {age} years old.".format("Alice", age=30)
print(formatted_string)

输出:

My name is Alice and I am 30 years old.

格式化数字

.format()方法提供了多种格式化数字的方式。

浮点数
pi = 3.141592653589793
formatted_string = "Pi to three decimal places: {:.3f}".format(pi)
print(formatted_string)

输出:

Pi to three decimal places: 3.142
整数
number = 42
formatted_string = "The number is: {:d}".format(number)
print(formatted_string)

输出:

The number is: 42
百分比
percentage = 0.85
formatted_string = "Success rate: {:.1%}".format(percentage)
print(formatted_string)

输出:

Success rate: 85.0%

字符填充与对齐

使用冒号 : 后面的格式说明符,可以指定字符填充、对齐和宽度。

左对齐
formatted_string = "{:<10}".format("left")
print(f"'{formatted_string}'")

输出:

'left      '
右对齐
formatted_string = "{:>10}".format("right")
print(f"'{formatted_string}'")

输出:

'     right'
居中对齐
formatted_string = "{:^10}".format("center")
print(f"'{formatted_string}'")

输出:

'  center  '
填充字符
formatted_string = "{:*^10}".format("center")
print(f"'{formatted_string}'")

输出:

'**center**'

嵌套字段

可以在格式化字符串中嵌套字段。

data = {
    'first': 'Hello',
    'second': 'World'
}
formatted_string = "{first} {second}".format(**data)
print(formatted_string)

输出:

Hello World

示例总结

name = "Alice"
age = 30
pi = 3.14159
formatted_string = "Name: {0}, Age: {1}, Pi: {2:.2f}".format(name, age, pi)
print(formatted_string)

输出:

Name: Alice, Age: 30, Pi: 3.14

.format()方法非常强大且灵活,适用于各种字符串格式化需求。通过掌握这些用法,你可以更高效地处理字符串。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值