How can I clean up these print statements?

Question:

So, I’m playing with .csv files learning how to read and present the info. I’m printing the results to the terminal, but as I print more content, I have a wall of print statments that just keeps getting longer and longer. Is there any way to clean this up? Also, please ignore my vulgar data. I generated that csv at like 3AM.

print("")
print(people[owner]["first_name"], end = "")
print(" ", end="")
print(people[owner]["last_name"], end="")
print(" owns the most buttplugs with a total of ",end="")
print(people[owner]["plugs"], end="")
print(" buttplugs!")
print("That's ",end="")
print(people[owner]["plugs"] - round(get_avg(people)),end="")
print(" more buttplugs than the average of ",end="")
print(round(get_avg(people)),end="")
print("!")
print("")
# Result: Sonnnie Mallabar owns the most buttplugs with a total of 9999 buttplugs!
# That's 4929 more buttplugs than the average of 5070
Asked By: Ryan

||

Answers:

f-strings are what you are looking for. They allow you to easily format your code in a very readable manner. Example:

print(f'{people[owner]["first_name"]} won the prince...')
Answered By: Einliterflasche
avg = round(get_avg(people))
plugs = people[owner]['plugs']
print(
    f'n{people[owner]["first_name"]} {people[owner]["first_name"]} '
    f'owns the most buttplugs with a total of {plugs} buttplugs!n'
    f"That's {plugs - avg} more buttplugs than the average of {avg}!"
)

prints

Sonnnie Sonnnie owns the most buttplugs with a total of 9999 buttplugs!
That's 4929 more buttplugs than the average of 5070!
Answered By: Michael Hodel

You could combine them into 2 print statements. Each comma will take care of a space in between, and you have to convert numbers to string

print(people[owner]["first_name"], people[owner]["last_name"], "owns the most buttplugs with a total of", str(people[owner]["plugs"]), "buttplugs!")
print("That's", str(people[owner]["plugs"] - round(get_avg(people))), "more buttplugs than the average of", str(round(get_avg(people))), "!")

or 2 statements using f-string

first_name = people[owner]["first_name"]
last_name = people[owner]["last_name"]
total = people[owner]["plugs"]
diff = people[owner]["plugs"] - round(get_avg(people))
avg = round(get_avg(people))
print(f"{first_name} {last_name} owns the most buttplugs with a total of {total} buttplugs!")
print(f"That's {diff} more buttplugs than the average of {avg}!")
Answered By: Gold79
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.