简体   繁体   English

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

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

What is the point of using code, like on line 8 and 9, when we can use print like on line 10? 当我们可以像第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

What you're seeing on lines 8-9 are called formatted string literals or f-strings for short. 在第8-9行中看到的内容称为格式化字符串文字或简称为f字符串 They were added to Python in version 3.6, and detailed in PEP498 . 它们已在3.6版中添加到Python,并在PEP498中进行了详细说明 They basically allow you to embed expressions directly in strings. 它们基本上允许您将表达式直接嵌入字符串中。

What['s] the point of using line 8 and line 9 if we can just use line 10? 如果我们只能使用第10行,那么使用第8行和第9行有什么意义呢?

So, what is the point of using them over the normal call to print ? 那么,什么他们使用超过正常调用的点print In the example above, not much. 在上面的示例中,不多。 The real benefit is shown when you need to format strings using multiple values. 当您需要使用多个值格式化字符串时,将显示出真正的好处。 Rather than doing doing a bunch of string concatenation, you can directly use the name of a variable or include an expression in the string: 您可以直接使用变量名或在字符串中包含表达式,而不必进行一堆字符串连接:

>>> 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'

Although is may be hard to tell from the above examples, f-strings are very powerful . 尽管从上面的示例可能很难分辨,但是f字符串非常强大 Being able to embed entire expressions inside of a string literal is a very useful feature, and can also make for more clear and concise code. 能够将整个表达式嵌入到字符串文字中是非常有用的功能,并且还可以使代码更清晰简洁。 This will be become very clear when you begin to write more code and the use cases for your code becomes non-trivial. 当您开始编写更多代码并且代码的用例变得不平凡时,这一点将变得非常清楚。

In short, they allow you to format your strings. 简而言之,它们允许您格式化字符串。 If you need formatting then (for example) 如果您需要格式化,那么(例如)

print(f"hello {world}")

returns 退货

hello world 你好世界

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

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