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 trialSam Dale
6,136 PointsPython str.format versus concatenation
Hi there. So I always notice that Kenneth consistently uses str.format to show variables within strings. When I dink around with Python on my own, I usually use concatenation, because it puts the variable name where it should actually be inserted. </br>Kenneth's way:
new_item = "apples"
print("Your new item is {}. ".format(new_item))
How I would be more inclined to do it:
new_item = "apples"
print("Your new item is " + new_item + ". ")
Is either more professional/more common in the Python community or does it just come down to a personal style choice? Thanks!
1 Answer
Andreas cormack
Python Web Development Techdegree Graduate 33,011 PointsHi Sam
I personally like the format method mostly because i can insert variables exactly where i want to in a string. It also come really handy if you want to unpack a dictionary. Consider this example below
#function thats takes a dictionary as a argument
def my_details(dict):
return("My name is {name} and i was born on {dob}!".format(**dict))
print(my_details({"name":"heman","dob":"who knows"}))
Output is : My name is heman and i was born on who knows!
# consider this case too
name = "heman"
dob = "who knows"
# i want to insert these variables in a string but i have to watch where the " end and start inorder to get the spacing correct
"My name is "+name+" and i was born on "+dob
# consider the format function its much easier, i dont need to worry about spacing as such
"I am {} and i was born on {}".format(name,dob)
so format is alot more handy a function to use not to meantion it makes inserting variables in a string so easy.
Sam Dale
6,136 PointsSam Dale
6,136 PointsThat really makes a lot of sense (and the example was really clear). Thank you!