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 trialMyles Brathwaite
1,971 PointsDifference between f'str' and format method?
I am confused between the use of f 'str' and the format method as they seem like they serve the same purpose. Is there a situation where the format method is the better option to use over the f 'str'? Example given below
groceries = ['roast beef', 'cucumbers', 'lettuce', 'peanut butter', 'bread', 'dog food']
index = 1
for item in groceries:
print(f'{index}. {item}')
index += 1
count = 1
for item in groceries:
print("{}. {}".format(index, item))
count += 1
1 Answer
Chris Freeman
Treehouse Moderator 68,423 PointsThe newer f-string
format has faster execution and is more readable in many cases. The format()
method is still useful when you want to unpack a container (list
, str
, etc.)
# using format
>>> s= 'abcde'
>>> s
‘abcde’
>>> print('{}-{}-{}'.format(*s[1:4]))
b-c-d
# using f-string It would more typing
>>> print(f'{s[1]}-{s[2}-{s[3]}')
b-c-d
# or using clearer when adding a step
>>> x, y, z = s[1:4]
>>> x, y, z
(‘b’, ‘c’, ‘d’)
>>> print(f'{x}-{y}-{z}')
b-c-d
Post back if you need more help. Good luck!!!