天天看點

python中str.format_Python中字元串格式化str.format的詳細介紹

前言

Python 在 2.6 版本中新加了一個字元串格式化方法:str.format() 。它的基本文法是通過 {} 和 : 來代替以前的 %.。

格式化時的占位符文法:

replacement_field ::= "{" [field_name] ["!" conversion] [":" format_spec] "}"

“映射”規則

通過位置

str.format()可以接受不限個參數,位置可以不按順序:

>>> "{0} {1}".format("hello", "world")

'hello world'

>>> "{} {}".format("hello", "world")

'hello world'

>>> "{1} {0} {1}".format("hello", "world")

'world hello world'

通過關鍵字參數

使用關鍵參數時字元串中需要提供參數名:

>>> "I am {name}, age is {age}".format(name="huoty", age=18)

'I am huoty, age is 18'

>>> user = {"name": "huoty", "age": 18}

>>> "I am {name}, age is {age}".format(**user)

'I am huoty, age is 18'

通過對象屬性

str.format()可以直接讀取使用者屬性:

>>> class User(object):

... def __init__(self, name, age):

... self.name = name

... self.age = age

...

... def __str__(self):

... return "{self.name}({self.age})".format(self=self)

...

... def __repr__(self):

... return self.__str__()

...

...

>>> user = User("huoty", 18)

>>> user

huoty(18)

>>> "I am {user.name}, age is {user.age}".format(user=user)

'I am huoty, age is 18'

通過下标

在需要格式化的字元串内部可以通過下标來通路元素:

>>> names, ages = ["huoty", "esenich", "anan"], [18, 16, 8]>>> "I am {0[0]}, age is {1[2]}".format(names, ages)

'I am huoty, age is 8'

>>> users = {"names": ["huoty", "esenich", "anan"], "ages": [18, 16, 8]}

>>> "I am {names[0]}, age is {ages[0]}".format(**users)

指定轉化

可以指定字元串的轉化類型:

conversion ::= "r" | "s" | "a"

其中 “!r” 對應 repr(); “!s” 對應 str(); “!a” 對應 ascii()。 示例:

>>> "repr() shows quotes: {!r}; str() doesn't: {!s}".format('test1', 'test2')

"repr() shows quotes: 'test1'; str() doesn't: test2"

格式限定符

填充與對齊