简体   繁体   中英

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?

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. They were added to Python in version 3.6, and detailed in 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?

So, what is the point of using them over the normal call to 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 . 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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