Videos
Can someone explain in just simple terms what the purpose of the f-string does. I know how to write it in and stuff just what does it help do that makes it a better alternative let’s say in this scenario:
print(‘Movie ticket price:’, movie_ticket_price) or print(f’Movie ticket price: {movie_ticket_price}’)
This is called f-strings and are quite straightforward : when using an "f" in front of a string, all the variables inside curly brackets are read and replaced by their value. For example :
age = 18
message = f"You are {age} years old"
print(message)
Will return "You are 18 years old"
This is similar to str.format (https://docs.python.org/3/library/stdtypes.html#str.format) but in a more concise way.
String starting with f are formatted string literals.
Suppose you have a variable:
pi = 3.14
To concatenate it to a string you'd do:
s = "pi = " + str(pi)
Formatted strings come in handy here. Using them you can use this do the same:
s = f"pi = {pi}"
{pi} is simply replaced by the value in the pi
Sorry for what's probably a very dumb question. I've just never seen it explained. :)
Hello i am a very very beginner coder. I’m in a beginner python class and I feel like the text books just throws stuff at concepts. Why are f’strings important? If I’m understanding it right I feel like the same output could get accomplished in a different way.