A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

afjah

初级黑马

  • 黑马币:

  • 帖子:

  • 精华:

© afjah 初级黑马   /  2019-5-31 22:50  /  1057 人查看  /  3 人回复  /   1 人收藏 转载请遵从CC协议 禁止商业使用本文

%格式化并不是很好,因为它很冗长并且容易导致错误,比如没有正确显示元组或字典,
str.format() 是对 %格式化 的改进,它使用普通函数调用语法,并且可以通过 __format__() 方法为对象进行扩展,str.format() 比 %格式化高级了一些,但是它在处理多个参数和更长的字符串时仍然可能非常麻烦,
而 f-Strings,它可以使得字符串格式化更加容易,f-strings 是指以 f 或 F 开头的字符串,其中以 {} 包含的表达式会进行值替换
f-Strings 使用方法:
>>> name = 'hoxis'
>>> age = 18
>>> f"hi, {name}, are you {age}"
'hi, hoxis, are you 18'
>>> F"hi, {name}, are you {age}"
'hi, hoxis, are you 18'
因为 f-strings 是在运行时计算的,那么这就意味着你可以在其中放置任意合法的 Python 表达式,比如:
1.运算表达式
>>> f"{ 2 * 3 + 1}"
'7'
2.调用函数
>>> def test(input):
...             return input.lower()
...
>>> name = "Hoxis"
>>> f"{test(name)} is handsome."
'hoxis is handsome.'
也可以直接调用内置函数
>>> f"{name.lower()} is handsome."
'hoxis is handsome.'
3.在类中使用
>>> class Person:
...            def __init__(self,name,age):
...                  self.name = name
...                  self.age = age
...           def __str__(self):
...                 return f"{self.name} is {self.age}"
...           def __repr__(self):
...                 return f"{self.name} is {self.age}. HAHA!"
...
>>> hoxis = Person("hoxis",18)
>>> f"{hoxis}"
'hoxis is 18'
>>> f"{hoxis!r}"
'hoxis is 18. HAHA!'
>>> print(hoxis)
hoxis is 18
>>> hoxis
hoxis is 18. HAHA!
4.多行 f-string
>>> name = 'hoxis'
>>> age = 18
>>> status = 'Python'
>>> message = {
...               f'hi {name}.'
...               f'you are {age}.'
...               f'you are learning {status}.'
... }
>>>
>>> message
{'hi hoxis.you are 18.you are learning Python.'}
每行都要加上 f 前缀,否则格式化会不起作用
>>> message = {
...               f'hi {name}.'
...               'you are learning {status}.'
... }
>>> message
{'hi hoxis.you are learning {status}.'}

可以在字符串中使用各种引号,只要保证和外部的引号不重复即可
>>> f"{'hoxis'}"
'hoxis'
>>> f'{"hoxis"}'
'hoxis'
>>> f"""hoxis"""
'hoxis'
>>> f'''hoxis'''
'hoxis'
那如果字符串内部的引号和外部的引号相同时呢?那就需要 \ 进行转义
>>> f"You are very \"handsome\""
'You are very "handsome"'
若字符串中包含括号 {},那么你就需要用双括号包裹它(三个括号包裹效果一样)
>>> f"{{74}}"
'{74}'

>>> f"{{{74}}}"
'{74}'
用反斜杠进行转义字符,但是不能在 f-string 表达式中使用,可以先在变量里处理好待转义的字符,然后在表达式中引用变量
>>> name = '"handsome"'
>>> f'{name}'
'"handsome"
不能在表达式中出现 #,否则会报出异常
所以f-string 比 %格式化方法和 str.format() 都要快,并且f-string 非常简洁实用、可读性高,而且不易出错

3 个回复

倒序浏览
预测未来最好的方法就是去创造未来。
回复 使用道具 举报
不要等待机会,而是要创造机会。现在我来了,希望我们都可以坚持,早日用知识达到暴富
回复 使用道具 举报
预测未来最好的方法就是去创造未来。
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马