首页 > 编程 > Python > 正文

Python中字符串格式化str.format的详细介绍

2020-02-23 04:23:04
字体:
来源:转载
供稿:网友

前言

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)>>> userhuoty(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"

格式限定符

填充与对齐

填充常跟对齐一起使用。^, <, > 分别是居中、左对齐、右对齐,后面带宽度, : 号后面带填充的字符,只能是一个字符,不指定则默认是用空格填充。

>>> "{:>8}".format("181716")' 181716'>>> "{:0>8}".format("181716")'00181716'>>> "{:->8}".format("181716")'--181716'>>> "{:-<8}".format("181716")'181716--'>>> "{:-^8}".format("181716")'-181716-'>>> "{:-<25}>".format("Here ")'Here -------------------->'

浮点精度

用 f 表示浮点类型,并可以在其前边加上精度控制:

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表