Search code examples
pythonstringf-string

Why do we need to put apostrophes around an f string in python?


I understand what f strings are and how to use them, but I do not understand why we need to have apostrophes around the whole f string when we have already made the variables a string.

first_name = 'Chris'
last_name = 'Christie'

sentence = f'That is {first_name} {last_name}'

I understand what the expected result is going to be. But here's where I'm confused. Aren't the variables first name and last name already a string? So when we put it into the f string statement, aren't we putting two strings (the variables first name and last name) inside one big string (as the whole f string statement is surrounded by apostrophes)? Sorry if this is confusing


Solution

  • Do not get confused about apostrophes:

    • We use apostrophes to define strings in Python:

      name = "Chris"
      
    • We use f-Strings as it is the new and improved way of formatting Strings in Python:

      # Define two strings
      name = "Chris"
      surname = "Christie"
      
      # Use f-Strings to format the overall sentence
      sentence = f"Hello, {name} {surname}"
      
      # Print the computed sentence 
      print(sentence)
      

      Output: 'Hello, Chris Christie'