How to avoid concatenation errors in Python using F-Strings!
CoolJames1610 (645)

How to avoid concatenation errors in Python using F-Strings!

So when they teach you Python, the "name and age" example always crops up:

name = input("What is your name? ")
age = int(input("How old are you? "))
print("Hello " + name + "! You are " + str(age) + " years old!")

Now I am sure a lot of people have made (and continue to make) the same mistake of forgetting to concatenate age (or any non-string character) to a string and then the program always breaks down. 😤😤😤😤😤😤😤😤 Very annoying right?

So, I am here to tel you A MUCH EASIER, LESS 😤😤😤😤😤😤 WAY to concactenate integers and strings.

Behold...

F-STRINGS!!!!

F-Strings are a way of formatting strings in Python, and if you want to know more about them then here is a good place to start.

Okay so, how do I make sure I don't get the concatenation error?

Simply like this:

name = input("What is your name? ")
age = int(input("How old are you? "))
print(f"Hello {name}! You are {age} years old!")

EASY RIGHT?

So, if you want the string to be in format mode then you simply place an f before your " or '.
Any values that you do not necessarily know, you place in-between curly brackets ({}).
And the good thing about this is that you do not need to remember to place str() before an integer!

GREAT INNIT?


Well that's the end of this relatively short tutorial.

If you have any questions, don't hesitate to comment for help!

Thank you :D

You are viewing a single comment. View All
MarcusWeinberger (589)

Very neat! You can also do:

x = 32 * 5
print(f"{x=}")

And it will output x=160