Strings vs f-strings

Hello, thanks for viewing this!
I am starting on the CompSci path and have learned a bit using Python Crash Course (PCC) before hand. In PCC, any arguments that involved variables and strings would utilize F-strings. The codecademy course for Hello World handles this a bit differently.

In Codecademy:

my_name = “Jake Golliher”
print("Hello and welcome " + my_name + “!”)


My Name = ‘Jake Golliher’
print(f"Hello and welcome {my_name}!")

Is one method “right” or “better”? I kind of prefer the f-string way since it makes it easy to add methods. Like this:

My Name = ‘Jake Golliher’
print(f"Hello and welcome {my_name.title()}!")

I think starting out, standard concatenation is easier to understand, and Codecademy covers f-strings too.
I think f-strings are generally more useful.

Another thing to consider is f-strings are relatively new to Python so you may work on old code which uses the other method

1 Like

Got it, thank you!
From what I know so far(not much), I’d agree.

Can’t old code use the .format() method as well? Or is standard concatenation more popular in old code?

1 Like

I’ve no idea as to what’s more popular, just that if you work on old code you’d need to the different methods they might use.

1 Like

Using .format is pretty common in old and newer code, it’s also the more portable one since it works in python2 and python3. In much older code you might still find string interpolation, e.g. "%d" %var. Unless you’re very unlucky there’s no reason you’d need it though (general advice is not to use it but it still crops up from time to time, even in the standard modules).

I think the nicer bit about .format or f-strings is that you don’t need as many calls to str(var) in order to build the string. If you’re joining one or two strings there’s absolutely nothing wrong with +, if you’re joining lots of strings then "".join might be a good one and if you’re using a variety of variables (not just strings) then the advanced formatting tends to be better. General Python advice would be to go whatever seems more readable :person_shrugging:.

1 Like

Very informative. Thank you!

1 Like