Creating Mad Libs using ‘F-strings’

What is F-String?
An F-String is a formatting concept that allows us to call upon Python functions within strings of text. F-string stands for ‘Formatted string’.  The use of F-string is only available in Python version 3.6 and above. Previously to this, you would have had to use .format() instead. A more up to date version of Python can be downloaded from https://www.python.org

To create a Mad Lib using an F-string, we first need to create a couple of variables that will be used in our string of text. In this example we’re going to be using two variables. A subject and a noun.

Creating Variables

Once the variables have been created, it is time to implement the ‘f-string’. F-strings are easy to spot within the program, as they always start with a letter ‘f’ and the string of text that follows is in speech marks or single quotes. Like so: mad_lib = f”string of {subject}”

Mad_lib

The curly brackets ‘{}’ are required to import the variable that was created earlier. When the program is run, the curly brackets will be replaced by the text the user entered.

Finally, to run the program, a regular print statement is needed.

Print Statement

If everything has been written correctly, and no errors have been reported. When the program runs, the output should look something similar to the image below.

If you are using a version of Python that is older than 3.6. You can create a similar program, however, its layout will look slightly different.

Format String

The ‘.format()’ approach will still work if you are using a version of Python that is later than 3.6. It differs from ‘f-string’ in that the curly brackets are left blank and that they are specified at the end of the string. Once the variables have been created, they can be used in any order. Simply by putting: .format(subject, name) would change the layout of the sentence.

Format Output

It doesn’t matter which version you use to create the Mad Lib. Both of the program’s outputs are identical achieve the same goal.

Published by Daniel Wray

IT Support Engineer; Studying for CompTIA Network+. 100 Days of Python Challenge. Aspiring blogger. Passion for Learning and Teaching! https://ko-fi.com/danielwray4

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: