string.format()用法,Python 中用于格式化字符串

string.format() 是 Python 中用于格式化字符串的一个方法。它允许你创建一个字符串,其中包含一些“占位符”,这些占位符将被 format() 方法中的参数替换。这使得创建包含动态数据的字符串变得非常容易和直观。

以下是一些 string.format() 的基本用法和示例:

基本用法
python

简单的占位符替换

formatted_string = "Hello, {}!".format("world")
print(formatted_string) # 输出: Hello, world!

使用位置参数

formatted_string = "The {} {} jumps over the {}.".format("quick", "brown fox", "lazy dog")
print(formatted_string) # 输出: The quick brown fox jumps over the lazy dog.

使用关键字参数(命名占位符)

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.
访问元组和列表元素
python

访问元组元素

person = ("Alice", 30)
formatted_string = "My name is {0[0]}, and I am {0[1]} years old.".format(person)
print(formatted_string) # 输出: My name is Alice, and I am 30 years old.

访问列表元素

person_list = ["Alice", 30]
formatted_string = "My name is {0[0]}, and I am {0[1]} years old.".format(person_list)
print(formatted_string) # 输出同上
访问字典元素
python

访问字典元素

person_dict = {"name": "Alice", "age": 30}
formatted_string = "My name is {name}, and I am {age} years old.".format(**person_dict)
print(formatted_string) # 输出: My name is Alice, and I am 30 years old.
格式化数字
python

格式化浮点数

pi = 3.141592653589793
formatted_string = "Pi is approximately {:.2f}.".format(pi)
print(formatted_string) # 输出: Pi is approximately 3.14.

格式化整数为二进制、八进制或十六进制

number = 42
formatted_string = "The number {} in binary is {:#b}, in octal is {:#o}, and in hex is {:#x}.".format(number, number, number, number)
print(formatted_string) # 输出: The number 42 in binary is 0b101010, in octal is 0o52, and in hex is 0x2a.
填充和对齐
python

填充和对齐文本

formatted_string = "{:>10}".format("hello") # 右对齐,宽度为10
print(formatted_string) # 输出: " hello"

formatted_string = "{:<10}".format("hello") # 左对齐,宽度为10
print(formatted_string) # 输出: "hello "

formatted_string = "{:^10}".format("hello") # 居中对齐,宽度为10
print(formatted_string) # 输出: " hello "

formatted_string = "{:^10}".format("hello") # 使用作为填充字符,居中对齐,宽度为10
print(formatted_string) # 输出: "hello"
使用大括号 {} 本身作为文本
python

如果需要在格式化的字符串中包含大括号本身,可以使用双大括号 {{}}

formatted_string = "Braces: {{}} and more braces: {{{}}}".format("inner")
print(formatted_string) # 输出: Braces: {} and more braces: {inner}

注意:上面的输出中,内部的 {{}} 被解释为单个 {},而 {{{}}} 中的第一个 { 和最后一个 } 之间的部分被替换为 "inner"。

要得到真正的 {} 字符,你应该这样写:

formatted_string = "Braces: {{}}".format("")
print(formatted_string) # 输出: Braces: {}
string.format() 方法非常强大和灵活,它允许你以多种方式定制和格式化字符串。

posted @   白色墨水  阅读(38)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律
点击右上角即可分享
微信分享提示