打印和格式化字符串文本有什么区别?

2024-05-13 00:34:44 发布

您现在位置:Python中文网/ 问答频道 /正文

当我们可以像在第10行一样使用print时,使用代码的意义是什么呢?在

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

Tags: 代码nameagemylineblue意义he
2条回答

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

print(f"hello {world}")

退货

你好世界

您在第8-9行看到的内容称为格式化字符串文本f-strings。它们在3.6版中被添加到Python中,并在PEP498中进行了详细说明。它们基本上允许您直接在字符串中嵌入表达式。在

What['s] the point of using line 8 and line 9 if we can just use line 10?

那么,在对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-串非常强大。能够将整个表达式嵌入到字符串文本中是一个非常有用的特性,也可以使代码更加清晰和简洁。当您开始编写更多的代码并且代码的用例变得非常重要时,这一点将变得非常清楚。在

相关问题 更多 >