当我们可以使用第 8 行和第 9 行代码时,使用代码有什么意义print
比如10号线?
my_name = 'Zed A. Shaw'
my_age = 35
my_height = 74
my_weight = 180
my_eyes = 'Blue'
my_teeth = 'White'
my_hair = 'Brown'
print(f"Let's talk about {my_name}.") # Line 8
print(f"He's {my_height} inches tall.") # Line 9
print("He's", my_teeth, "pounds heavy.") # Line 10
您在第 8-9 行看到的内容称为格式化字符串文字 or F 弦简而言之。它们在 Python 3.6 版本中被添加,详细信息参见PEP498 https://www.python.org/dev/peps/pep-0498/。它们基本上允许您将表达式直接嵌入到字符串中。
如果我们可以只使用第 10 行,那么使用第 8 行和第 9 行有什么意义呢?
所以呢is在正常调用中使用它们的要点print
?在上面的例子中,没有太多。当您需要使用多个值格式化字符串时,真正的好处就会显现出来。您可以直接使用变量的名称或在字符串中包含表达式,而不是进行一堆字符串连接:
>>> a = 12
>>> b = 6
>>> f'The sum of 12 and 6 is: {a + b}'
'The sum of 12 and 6 is: 18'
>>> name = 'Bob'
>>> age = 32
>>> f'Hi. My name is {name} and my age is {age}'
'Hi. My name is Bob and my age is 32'
>>> def fib(n):
if n <= 1:
return 1
return fib(n - 1) + fib(n - 2)
>>> f'The Fibonacci number of 10 is: {fib(10)}'
'The Fibonacci number of 10 is: 89'
虽然从上面的例子中很难看出,f 弦非常强大。能够将整个表达式嵌入字符串文字中是一个非常有用的功能,并且还可以使代码更加清晰和简洁。当您开始编写更多代码并且代码的用例变得不平凡时,这一点将变得非常清楚。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)