DEV Community

Cover image for f-Strings print in Python 3.6+
Oscar Eduardo Bolaños Ocampo
Oscar Eduardo Bolaños Ocampo

Posted on • Edited on

f-Strings print in Python 3.6+

This is an easy way to print messages in Python. This kind of string needs an "f" to activate the curly brackets in the string for the print function. Let's begin with a simple example like this:

user_name = input("Hello!\nWhat is your name?\n:")

In[1]: Oscar

print(f"OK {user_name}!\nI'm a computer :)")

Out[1]: OK Oscar!
        I'm a computer :)
Enter fullscreen mode Exit fullscreen mode

We can use other ways to declare a string with the same result:

value = 3.14159
print(f'{value}')
print(f"pi = {value}")
print(f"""The Pi constant:
this is an approximation: {value}""")
Enter fullscreen mode Exit fullscreen mode

We must be careful with the variable inside of the curly brackets because if doesn't exist a SyntaxError will pop up from python, ok that's all also you can use multiples values in a single f-string.

def plus_one(value: int) -> int:
    """sum 1 to input
       input: a number
       output: number + 1"""
    return value + 1


user_name = input("Hello!\nWhat is your name?\n:")
try:
    number = '2'
    ans = plus_one(number)

except Exception as err:
    print(f""">>> Message:
plus_one function doesn't work with {number} like input.
Here is the error honey:
{err}""")

else:
    print(f"Ok {user_name}, {number} plus_one is {ans}.")

finally:
    print("Bye!")
Enter fullscreen mode Exit fullscreen mode

Thanks for reading!

Top comments (0)