python format 用法及使用

本文介绍了Python中字符串格式化的几种方式,包括不设置指定位置的默认顺序格式化,通过索引设置位置的格式化,使用字典和列表索引设置参数,以及使用`str.format()`方法格式化数字。示例代码展示了各种用法,帮助理解字符串格式化的灵活性。
  • 不设置指定位置,按默认顺序
  • 设置指定位置
  • 字典设置参数
  • 列表索引设置参数
  • 传入对象
  • str.format() 格式化数字
>>>"{} {}".format("hello", "world")    # 不设置指定位置,按默认顺序
'hello world'
 
>>> "{0} {1}".format("hello", "world")  # 设置指定位置
'hello world'
 
>>> "{1} {0} {1}".format("hello", "world")  # 设置指定位置
'world hello world'

class AssignValue(object):
    def __init__(self, value):
        self.value = value
my_value = AssignValue(6)
print('value 为: {0.value}'.format(my_value))  # "0" 是可选的

>>> print("{:.2f}".format(3.1415926))
3.14
### Python 中 `format` 方法的用法详解 Python 的字符串格式化功能非常强大,可以灵活地将变量嵌入到字符串中。以下是对 `format` 方法的详细解析: #### 1. 基本用法:通过位置填充 `format` 方法支持通过位置索引来填充字符串中的占位符 `{}`。例如: ```python print('hello {0} i am {1}'.format('world', 'python')) # 输出: hello world i am python print('hello {} i am {}'.format('world', 'python')) # 输出: hello world i am python ``` 上述代码展示了如何通过位置参数自动填充占位符[^1]。 还可以重复使用同一个位置参数: ```python print('hello {0} i am {1}. a new language-- {1}'.format('world', 'python')) # 输出: hello world i am python. a new language-- python ``` #### 2. 使用解包操作填充 在 `format` 方法中,可以结合解包操作符 `*` 和 `**` 来填充列表、元组或字典中的值。 - **列表/元组解包**: ```python foods = ['fish', 'beef', 'fruit'] s = 'i like eat {} and {} and {}'.format(*foods) print(s) # 输出: i like eat fish and beef and fruit s = 'i like eat {2} and {0} and {1}'.format(*foods) print(s) # 输出: i like eat fruit and fish and beef ``` 这里通过 `*` 解包了列表 `foods` 的元素,并按照指定顺序填充到占位符中[^2]。 - **字典解包**: ```python dict_temp = {'name': 'Lily', 'age': 18} s = 'My name is {name}, i am {age} years old'.format(**dict_temp) print(s) # 输出: My name is Lily, i am 18 years old ``` 字典需要通过 `**` 进行解包,并且字典中的键名必须与占位符中的名称一致。 #### 3. 自定义占位符顺序 可以通过显式指定占位符的位置来控制输出顺序: ```python print('{0},{1},{2}'.format('a', 'b', 'c')) # 输出: a,b,c print('{2},{1},{0}'.format('a', 'b', 'c')) # 输出: c,b,a print('{2},{1},{0}'.format(*'abc')) # 输出: c,b,a print('{0}{1}{0}'.format('aa', 'bb')) # 输出: aabbaa ``` 上述代码展示了如何通过调整占位符的索引来自定义输出顺序[^3]。 #### 4. 格式化数字 `format` 方法还支持对数字进行格式化: ```python # 浮点数格式化 print('The value is {:.2f}'.format(3.14159)) # 输出: The value is 3.14 # 整数格式化 print('The value is {:d}'.format(123)) # 输出: The value is 123 # 科学计数法 print('The value is {:.2e}'.format(123456789)) # 输出: The value is 1.23e+08 ``` #### 5. 对齐和宽度控制 可以使用 `:<`、`:>`、`:^` 来控制对齐方式,以及指定字段宽度: ```python print('|{:<10}|'.format('left')) # 左对齐,总宽度为10 # 输出: |left | print('|{:>10}|'.format('right')) # 右对齐,总宽度为10 # 输出: | right| print('|{:^10}|'.format('center')) # 居中对齐,总宽度为10 # 输出: | center | ``` #### 6. 填充字符 除了默认的空格填充外,还可以指定其他字符作为填充: ```python print('|{:=^10}|'.format('center')) # 使用等号填充并居中 # 输出: |==center==| ``` ### 总结 `format` 方法是 Python 中一种强大的字符串格式化工具,支持通过位置、关键字、解包等方式填充占位符,并能够对数字、对齐方式等进行精确控制[^1][^2][^3]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值