-4

In the follow f-string,

print("It's fleece was white as {}.".format('snow'))

Is 'snow' a variable? I am confused with what exactly it would be judged as.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Harm
  • 11
  • 2
  • That's not an `f` string, that's a regular string literal on which the `str.format()` method is being called. No, `snow` is not a variable, it is another string literal. – Martijn Pieters May 21 '18 at 20:03
  • An `f` string starts with an `f`: `print(f"It's fleece was white as {'snow'}.")` – Martijn Pieters May 21 '18 at 20:03
  • @MartijnPieters Thank you so much for your help. I am just starting out with Python and i'm attempting to wrap my head around it. Clear and concise! :) – Harm May 21 '18 at 20:09

1 Answers1

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.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343