繁体   English   中英

print和格式化的字符串文字之间有什么区别?

[英]What is the difference between print and formatted string literals?

当我们可以像第10行那样使用print时,使用代码(如第8和9行)有什么意义呢?

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行中看到的内容称为格式化字符串文字或简称为f字符串 它们已在3.6版中添加到Python,并在PEP498中进行了详细说明 它们基本上允许您将表达式直接嵌入字符串中。

如果我们只能使用第10行,那么使用第8行和第9行有什么意义呢?

那么,什么他们使用超过正常调用的点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字符串非常强大 能够将整个表达式嵌入到字符串文字中是非常有用的功能,并且还可以使代码更清晰简洁。 当您开始编写更多代码并且代码的用例变得不平凡时,这一点将变得非常清楚。

简而言之,它们允许您格式化字符串。 如果您需要格式化,那么(例如)

print(f"hello {world}")

退货

你好世界

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM