Why does the python F string module not work?

Viewed 3898

I am making an adventure game in python 3.7.3, and I am using F strings for some of my print statements. When running it in the terminal and sublime text, F strings give me an error.

import time
from time import sleep
import sys

def printfast(str):
    for letter in str:
        sys.stdout.write(letter)
        sys.stdout.flush()
        time.sleep(0.04)

name = input("\nWhat is your name?\n\n")

printfast(f("You are the mighty hero {name}. In front of you, there is a grand palace, containing twisting marble spires and spiraling dungeons.\n")
3 Answers

You're doing it wrong. f isn't a function, it's more of an syntactic identifier. Whereas regular quotes " indicate the beginning of a regular string (or the end of any type of string), the token f" indicates the beginning of a format string in particular. The same idea goes for raw strings, indicated by r", or binary strings, indicated by b".

Instead of

f("You are...")

do

f"You are..."

In f("You ...), you're calling a function named f with the string as input parameter, and you don't have such a function hence the error.

You need to drop the enclosing parentheses () to make it a f-string:

f"You are the mighty hero {name}. In front of you, there is a grand palace, containing twisting marble spires and spiraling dungeons.\n"

f-strings are not created using a function, it's a type of string, which you denote using f'' (similar to b'' or r'')

So try using:

printfast(f"You are the mighty hero {name}. In front of you, there is a grand palace, containing twisting marble spires and spiraling dungeons.\n")
Related