Monday, March 18, 2024

f-strings

 

f-strings
f-strings (format strings) are the best way to combine variables and text together. Everything up until now has been...well...awkward.

Let's look at how we have combined variables and text in the past...concatenating.
name = "Katie"
age = "28"
pronouns = "she/her"

print("This is", name, "using", pronouns, "pronouns and is age", age)

Let's now use an f-string for this same code. What changes did I make to this code?

 Change 1: Using {} as a placeholder for the variable.
 Change 2: Adding .format(variable names, commas)

name = "Katie"
age = "28"
pronouns = "she/her"

print("This is {}, using {} pronouns, and is {} years old.".format(name, pronouns, age))

Local Variables

We can set local variables within the f-string itself. Now it doesn't matter the order of the variables.
 Looking at this code again, I can set my variables inside the text itself. 

Change 1: Replace {}with variable names. 
Change 2: Replace each variable inside {} with what has been defined in format.( = )

name = "Katie"
age = "28"
pronouns = "she/her"
print("This is {name}, using {pronouns} pronouns, and is {age} years old. Hello, {name}. How are you? Have you been having a great {age} years so far".format(name=name, pronouns=pronouns, age=age))

  • f-strings work with different variable types too: int, float, and string.
name = "Katie"
age = "28"
pronouns = "she/her"

response = "This is {name}, using {pronouns} pronouns, and is {age} years old. Hello, {name}. How are you? Have you been having a great {age} years so far".format(name=name, pronouns=pronouns, age=age)

print(response)

The Power of f...
Instead of all that faffing about...try this instead.

Use the letter f before any string with {} for variable names (and forget that .format business).



Look at this same code and see the difference using this technique

name = "Katie"
age = "28"
pronouns = "she/her"
response = f"This is {name}, using {pronouns} pronouns, and is {age} years old. Hello, {name}. How are you? Have you been having a great {age} years so far"
print(response)

Alignment of arguments in print function

left = <  ,   right = >  ,   center = ^

for i in range(1, 31):
print(f"Day {i} of 30")

Let's fix it by adding a left alignment of 2 characters long.

for i in range(1, 31):
print(f"Day {i: <2} of 30")

Coding challenge :
Create a program that uses a loop that asks the user what they have thought of each of the 30 days of challenges so far.
For each day, prompt the user to answer a question and restate it in a full sentence that is center aligned underneath the heading.


print("30 Days Down - What did you think?")
print()
for i in range(1, 31):
thought = input(f"Day {i}:\n")
print()
myText = f"You thought Day {i} was"
print(f"{myText:^35}")
print(f"{thought:^35}")
print()

  2D Dictionaries Remember that dictionaries are very similar to lists, except that they store data as key:value pairs. The value is what it...