在线运行和编辑此教程中的代码
运行代码1.1. 语法
每条 f-string 语句由两部分组成:一是字符 f 或 F,二是需要格式化的字符串。该字符串可用单引号、双引号或三引号括起来。
来看一下语法。
## we can also use F, '', ''''', """"""'
f"string"
在 string 的位置,放入我们要进行格式化的句子。
2. 显示变量
我们过去主要使用 str.format() 方法来格式化字符串。但时代变了,如今有一种新方法能让我们的工作事半功倍。
放在花括号 { } 中的变量会像普通的 print 语句一样在输出中显示。来看一个例子。
## declaring variables
name = "Datacamp"
type_of_company = "Educational"
## enclose your variable within the {} to display it's value in the output
print(f"{name} is an {type_of_company} company.")
Datacamp is an Educational company.
我们在输出中得到了变量的值。很简单吧。同样我们也可以把 f 换成 F。
## declaring variables
name = "Datacamp"
type_of_company = "Educational"
## enclose your variable within the {} to display it's value in the output
print(F"{name} is an {type_of_company} company.")
Datacamp is an Educational company.
f 无论是小写还是大写,效果都相同。
3. 表达式
如果我们能在字符串中计算表达式(如算术、函数调用等)会怎样?是不是很酷!没错!在字符串中使用表达式非常有趣。f-string 允许我们在字符串内部对表达式求值。
只需把表达式放到 { } 中即可。f-string 会在程序运行时对其求值。这是一个出色的特性,既省时又省代码。
下面看看不同类型表达式的示例。
## arithmetic expression
print(f"{5 * 5}")
25
我们还可以在 { } 中调用函数。先定义一个函数 greet(),然后在 f-string 中调用它。
def greet(name):
return "Hello, " + name
## calling the function using f-string
name = "Datacamp"
print(f"{greet(name)}")
Hello, Datacamp
同样地,我们也可以调用内置方法。来看一下。
## calling the 'title' method which makes the first letter of every word upper
string = "datacamp is an educational company."
print(f"{string.title()}")
Datacamp Is An Educational Company.
f-string 还能做什么?能否显示对象?可以,方法与显示变量的输出相同。
class Sample:
def __init__(self, name, age):
self.name = name
self.age = age
## this method will be called when we print the object
def __str__(self):
return f'{self.name} is {self.age} years old.'
john = Sample("John", 19)
## it'll wake up the __str__() method
print(f"{john}")
John is 19 years old.
4. 特殊字符
如果我们想显示诸如 {}、\'、\" 这样的特殊字符,该怎么办?这些字符在 Python 内部有特殊含义。我们能在 f-string 中使用转义字符吗?下面来解答这些问题。
4.1. 引号
在 f-string 中可以使用任意引号标记(单引号、双引号或三引号)。打印引号时需要使用转义字符。f-string 表达式不允许在花括号内使用反斜杠,我们必须把它放在 { } 外部。
通过示例来看。
name = "Datacamp"
## displaying single quotations
print(f"Hello, \'{name}\'")
print()
## displaying double quotations
print(f"Hello, \"{name}\"")
Hello, 'Datacamp'
Hello, "Datacamp"
再看一些在 f-strings 中的其它引号形式。
f'{"Hello, Datacamp"}'
'Hello, Datacamp'
f"{'Hello, Datacamp'}"
'Hello, Datacamp'
f"""Hello, Datacamp"""
'Hello, Datacamp'
f'''Hello, Datacamp'''
'Hello, Datacamp'
我们也可以在三引号中包含 { }。
在 f-string 的 { } 内不能使用反斜杠。如果在 { } 中包含反斜杠,会报错。
print(f"{\"Datacamp\"}")
File "<ipython-input-60-b9a2502d6274>", line 1
print(f"{\"Datacamp\"}")
^
SyntaxError: f-string expression part cannot include a backslash
4.2. 花括号
如果要使用 f-string 打印花括号,需要成对使用双重花括号。看示例。
print(f"{{Datacamp}}")
{Datacamp}
如果您想用 f-string 显示两对花括号,就需要使用四对花括号。
print(f"{{{{Datacamp}}}}")
{{Datacamp}}
5. 字典
在 f-string 中处理字典键时需要稍微注意。字典键所用的引号应与 f-string 本身所用的引号不同。也就是说,不能为字典键使用与 f-string 相同的引号。
person = {"name": "John", "age": 19}
print(f"{person['name']} is {person['age']} years old.")
John is 19 years old.
在使用字典的情况下,不能像下面这样写。
person = {"name": "John", "age": 19}
print(f'{person['name']} is {person['age']} years old.')
File "<ipython-input-65-6849ff0810ae>", line 2
print(f'{person['name']} is {person['age']} years old.')
^
SyntaxError: invalid syntax
结语
希望您通过本教程在 Python 中学到了新知识。若想深入了解字符串及以往的格式化技术,请前往 Datacamp 的这篇教程。另外,也可查看 DataCamp 的 Regular Expressions in Python 课程。
祝您编码愉快 :)
1. 引言
什么是字符串格式化?
字符串格式化是指使用特定编程语言提供的格式化技术,将字符串以更美观、可读的方式呈现。在 Python 中有多种字符串格式化技术。接下来我们将探索一种新的 f-string 格式化技术。
f-string 会在程序运行时进行求值。与之前的方法相比,它的速度更快。
与 Python 之前的字符串格式化技术相比,f-string 的语法更简单。我们将通过不同的示例全面讲解这种格式化方式。