Debate: Print  Function Vs String Formatting Methods

Debate: Print Function Vs String Formatting Methods

Let's debate on this Christmas gist I have for you....

A friend of mine reached out to me last week for some help on objects and classes in Python. You know how OOP(Object Oriented Programming) could be quite frustrating at first...

Instead of using the return value, I used the print function - then i used the string formatting methods in some places.

What happened?

Now, that was the question my friend asked me when he saw me use the string formatting methods.

He told me, "I saw someone use it, but couldn't understand despite the person's explanation."

I told him, "Don't worry, it's quite easy to understand."

Don't get frightened dude - I've explained about a certain string formatting method here

Here's something I told him, "The string formatting methods gives you so many options to manipulate your output unlike the print function"

Why? Let's see some codes...

Examples with the Print function and String Formatting Methods

#Using the print function

school = "Maryland College"
print("The name of my school,", school) 

#or
print(school, ",The name of my school.")

#output 1
The name of my school, Maryland College

#output 2
Maryland College, The name of my school.

Take a look at the print function - you're just limited to two ways of printing the output to the user.

But...The string formatting methods allow you manipulate your output to your own taste.

## Using the Str.format() Method

school = "Maryland College"

print("{} is the name of my school".format(school))
print("The name of my school is {}".format(school))
print("The name {} is my school".format(school))

#Using the f'string interpolation method

school = "Maryland College"
print(f"{school} is the name of my school")
print(f"The name of my school is {school}")
print(f"The name {school} is my school")

#Ouput
Maryland College is the name of my school
The name of my school is Maryland College
The name Maryland College is my school

Don't be surprised if you're a beginner - all you've to do is learn and use one of the string formatting methods in your next coding challenge or exercise.

Anything else?

Yes...There are still more more manipulations you can execute via the string formatting methods. Check out W3 schools, real python, geeksforgeeks, programmiz blogs.

Conclusion

The string formatting methods definitely style your codes better as a developer. So, have you decided what method you'll go for? Or do you still want to stick with the print function?

Have a fun-fillled Christmas celebration coding....