Python And F-strings Explanation
Solution 1:
No, 'snow'
is a string literal, an expression that produces a string value. snow
would be a variable name (note the lack of quotes).
Compare:
>>>'snow'
'snow'
>>>snow
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'snow' is not defined
>>>snow = 42>>>snow
42
>>>snow = 'snow'>>>snow
'snow'
The variable snow at first wasn't yet assigned to, so trying to use it caused an exception. I then assigned an integer to the name, and then the string with value 'snow'
.
Formatting a string literal with another string literal is pretty meaningless. You'd normally use an actual variable, so you can vary the output produced:
compared_to = 'snow'print("It's fleece was white as {}.".format(compared_to))
Also, that's not an f
string. An f
string literal starts with a f
character. What you have here is a regular, run-of-the-mill string literal, and a call to the str.format()
method. The following is the equivalent expression using an f-string:
print(f"It's fleece was white as {'snow'}.")
See String with 'f' prefix in python-3.6 for more information on actual f-strings.
Post a Comment for "Python And F-strings Explanation"