Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python

why are there so many methods for string formatting?

To learn to code in python I watched many tutorials online and found different ways of string formatting.

pet = "dog"
action = "bites"
print("I love " + pet + " but it "+ action)
print("I love {} but it {}".format(pet, action))
print("I love",pet,"but it",action)
print("I love %s but it %s" %(pet, action))
print("I love {pet} but it {action}".format(pet="cat", action="scratches"))

above print statements output the same result. why are there so many ways of string formatting. Which one is more pythonic? what are the significance of them? please answer my question. thank you!

1 Answer

Steven Parker
Steven Parker
243,266 Points

You didn't show my favorite, the "f-string":

print(f"I love {pet} but it {action}")

One might make a case for this being "most pythonic" because it's both the most modern and the most concise. But ultmately, it's "programmer's choice" which to use.

I tried that too but It didn't work at that time when I used workspaces. But I tried it again in idle now it works. Thank you Steven Parker.