python 字符串格式化的示例

一、旧式的字符串格式化

% 操作符

参考以下示例:

>>> name = "Eric"
>>> "Hello, %s." % name
'Hello, Eric.'

当有多个变量需要插入到字符串中时:

>>> name = "Eric"
>>> age = 74
>>> "Hello, %s. You are %s." % (name, age)
'Hello, Eric. You are 74.'

当需要替换的变量进一步增多时,使用 % 操作符格式化字符串会导致代码可读性变得很差:

>>> first_name = "Eric"
>>> last_name = "Idle"
>>> age = 74
>>> profession = "comedian"
>>> affiliation = "Monty Python"
>>> "Hello, %s %s. You are %s. You are a %s. You were a member of %s." % (first_name, last_name, age, profession, affiliation)
'Hello, Eric Idle. You are 74. You are a comedian. You were a member of Monty Python.'

str.format()

str.format() 是对 % 方式的改进,它使用常见的函数调用的语法,并且可以通过定义对象本身的 __format__() 方法控制字符串格式化的具体行为。

基本用法:

>>> name = "Eric"
>>> age = 74
>>> "Hello, {}. You are {}.".format(name, age)
'Hello, Eric. You are 74.'

str.format() 相对于 % 操作符有着更强的灵活性。比如可以通过数字索引来关联替换到字符串中的变量:

>>> name = "Eric"
>>> age = 74
>>> "Hello, {1}. You are {0}.".format(age, name)
'Hello, Eric. You are 74.'

为了提高代码可读性,{} 中也可以使用有具体含义的参数名:

>>> name = "Eric"
>>> age = 74
>>> "Hello, {name}. You are {age}".format(name=name, age=age)
'Hello, Eric. You are 74'

针对字典结构的数据:

>>> person = {'name': 'Eric', 'age': 74}
>>> "Hello, {name}. You are {age}.".format(name=person['name'], age=person['age'])
'Hello, Eric. You are 74.'

或者更简洁的方式:

>>> person = {'name': 'Eric', 'age': 74}
>>> "Hello, {name}. You are {age}.".format(**person)
'Hello, Eric. You are 74.'

问题在于当需要替换的变量很多时,str.format() 方式依然会导致代码变得过于冗长:

>>> first_name = "Eric"
>>> last_name = "Idle"
>>> age = 74
>>> profession = "comedian"
>>> affiliation = "Monty Python"
>>> "Hello, {first_name} {last_name}. You are {age}. \
  You are a {profession}. You were a member of {affiliation}."\
  .format(first_name=first_name, last_name=last_name, age=age, \
  profession=profession, affiliation=affiliation)
'Hello, Eric Idle. You are 74. You are a comedian. You were a member of Monty Python.'

二、f-string

基本用法

>>> name = "Eric"
>>> age = 74
>>> f"Hello, {name}. You are {age}."
'Hello, Eric. You are 74.'

嵌入表达式

>>> f"{2 * 37}"
'74'

>>> def to_lowercase(input):
...   return input.lower()

>>> name = "Eric Idle"
>>> f"{to_lowercase(name)} is funny"
'eric idle is funny'

>>> f"{name.lower()} is funny"
'eric idle is funny'

f-string 中还可以直接嵌入某个对象实例,只要其内部实现了 __str__ 或者 __repr__ 方法:

class Comedian:
  def __init__(self, first_name, last_name, age):
    self.first_name = first_name
    self.last_name = last_name
    self.age = age

  def __str__(self):
    return f"{self.first_name} {self.last_name} is {self.age}"

new_comedian = Comedian("Eric", "Idle", 74)
print(f"{new_comedian}")
# Eric Idle is 74

多行 f-string

>>> name = "Eric"
>>> profession = "comedian"
>>> affiliation = "Monty Python"
>>> message = (
...   f"Hi {name}. "
...   f"You are a {profession}. "
...   f"You were in {affiliation}."
... )
>>> message
'Hi Eric. You are a comedian. You were in Monty Python.'

参考资料

Python 3's f-Strings: An Improved String Formatting Syntax (Guide)

以上就是python 字符串格式化的示例的详细内容,更多关于python 字符串格式化的资料请关注我们其它相关文章!

(0)

相关推荐

  • Python中格式化字符串的四种实现

    关于Python的格式化字符串,几乎所有接触过Python语言的人都知道其中一种,即使用运算符%,但对于绝大多数初学者来说也仅此而已. 因此,本文将先总结如何通过%运算符来格式化字符串,同时指出这种方式的缺点,然后带你了解Python中另外三种强大的格式化字符串的方式:str.format().f-string以及模板字符串,并给出在何时选择何种方式的建议. 一.%运算符格式化字符串 1. 如何使用 字符串对象都有一个使用%运算符完成的內置操作,可被用来格式化字符串.最简单的如: In [11]

  • python字符串格式化方式解析

    1.%格式符 name = '李四' age = 18 a = "姓名:%s,年龄:%s"%(name,age) print(a) #姓名:李四,年龄:18 ​ b = "%(name)s,%(age)s"%{'name':'张三','age':18} print(b) #张三,18 这种格式化并不是很好,因为它很冗长并且容易导致错误,比如没有正确显示元组或字典 2.str.format() name = '李四' age = 18 # 替换字段用大括号进行标记 a

  • python3格式化字符串 f-string的高级用法(推荐)

    f-string,亦称为格式化字符串常量(formatted string literals),是Python3.6新引入的一种字符串格式化方法,该方法源于PEP 498 – Literal String Interpolation,主要目的是使格式化字符串的操作更加简便. f-string在形式上是以 f 或 F 修饰符引领的字符串(f'xxx' 或 F'xxx'),以大括号 {} 标明被替换的字段:f-string在本质上并不是字符串常量,而是一个在运行时运算求值的表达式: While ot

  • Python格式化字符串f-string概览(小结)

    简介 f-string,亦称为格式化字符串常量(formatted string literals),是Python3.6新引入的一种字符串格式化方法,该方法源于PEP 498 – Literal String Interpolation,主要目的是使格式化字符串的操作更加简便.f-string在形式上是以 f 或 F 修饰符引领的字符串(f'xxx' 或 F'xxx'),以大括号 {} 标明被替换的字段:f-string在本质上并不是字符串常量,而是一个在运行时运算求值的表达式: While

  • Python字符串格式化常用手段及注意事项

    格式化方式1: 使用f"" 使用示例 # -*- coding: utf-8 -*- # @Time : 2020/4/22 22:35 # @Author : chinablue # 替换变量 name = "chinablue" # 格式化字符串 res_str = f"hello {name}" print(res_str) 注意事项 %和format也是python常用的格式化字符串方式; 如果字符串中需要显示{},则通过{{}}来转义.

  • Python3中的f-Strings增强版字符串格式化方法

    在Python3.6提供f-Strings新的字符串格式化语法.不仅更加可读.简洁,相比其他方式也不易造成错误,而且还更快. 看完本文你将学习到如何以及为什么使用f-strings.正式开始之前,我们先看看之前格式化字符串语法. 1. 旧式字符串格式化 在Python3.6之前,主要有两种方式格式化字符串:%-格式化 和 str.format().下面我们先了解它们的用法以及局限性. 1.1 %-格式化 这时Python的官方字符串格式化方法,从语言开始时就存在.官方文档明确提出不建议使用,并其

  • python2与python3的print及字符串格式化小结

    最近一直在用python写程序,对于python的print一直很恼火,老是不按照预期输出.在python2中print是一种输出语句,和if语句,while语句一样的东西,在python3中为了填补python2的各种坑,将print变为函数,因此导致python3中print的一些使用和python2很不一样.同时,python3大改python2中的字符串格式化,主推format()函数格式,用法很是灵活,让老用户一时摸不着头脑.今天特来总结一样print和format,也希望能帮助大家彻

  • Python字符串格式化f-string多种功能实现

    f-string 格式化 f-string 格式化 就是在字符串模板前面加上f,然后占位符使用{} ,里面直接放入对应的数据对象. 如下所示 f'税前薪资是:{salary}元, 缴税:{tax}元, 税后薪资是:{aftertax}元' 完整的代码如下 salary = input('请输入薪资:') # 计算出缴税额,存入变量tax tax = int(salary) *25/100 # 计算出税后工资,存入变量aftertax aftertax = int(salary) *75/100

  • 使用Python将字符串转换为格式化的日期时间字符串

    我正在尝试将字符串"20091229050936"转换为"2009年12月29日(UTC)" >>>import time >>>s = time.strptime("20091229050936", "%Y%m%d%H%M%S") >>>print s.strftime('%H:%M %d %B %Y (UTC)') 给 AttributeError: 'time.str

  • Python字符串三种格式化输出

    字符串格式化输出是python非常重要的基础语法,今天就把三种格式化输出做一个简单的总结,希望对大家有帮助. 格式化输出:内容按照一定格式要求进行输出. 1.使用占位符%输出 python2.6版本之前,使用%格式化字符串沿用的是C语言的输出格式. 使用说明: print("格式化字符串" % 变量) #变量超过2个使用元组格式: print("格式化字符串" % (变量1,变量2)) 使用%占位符表示字符串中变量位置. 传入的值要与%占位符的变量一一对应. 其中,

  • Python之time模块的时间戳,时间字符串格式化与转换方法(13位时间戳)

    Python处理时间和时间戳的内置模块就有time,和datetime两个,本文先说time模块. 关于时间戳的几个概念 时间戳,根据1970年1月1日00:00:00开始按秒计算的偏移量. 时间元组(struct_time),包含9个元素. time.struct_time(tm_year=2017, tm_mon=10, tm_mday=1, tm_hour=14, tm_min=21, tm_sec=57, tm_wday=6, tm_yday=274, tm_isdst=0) 时间格式字

  • 浅析python3字符串格式化format()函数的简单用法

     format()函数 """ 测试 format()函数 """ def testFormat(): # format()函数中有几个元素,前面格式化的字符串中就要有几个 '{}' # 位置 s1 = 'a{}b{}c{}d{}'.format(1, 2, 3, 4) # 索引,format()函数中的元素,从0开始 s2 = 'a{0}b{1}c{3}d{2}'.format(1, 2, 3, 4) # 索引可以重复使用 s3 = 'a{0}

随机推荐