FAQ: String Methods - .format()

This community-built FAQ covers the “.format()” exercise from the lesson “String Methods”.

Paths and Courses
This exercise can be found in the following Codecademy content:

Computer Science

FAQs on the exercise .format()

Join the Discussion. Help a fellow learner on their journey.

Ask or answer a question about this exercise by clicking reply (reply) below!

Agree with a comment or answer? Like (like) to up-vote the contribution!

Need broader help or resources? Head here.

Looking for motivation to keep learning? Join our wider discussions.

Learn more about how to use this guide.

Found a bug? Report it!

Have a question about your account or billing? Reach out to our customer support team!

None of the above? Find out where to ask other questions here!

2 posts were split to a new topic: What are the backslashes in the string?

15 posts were split to a new topic: Why does the order of the arguments matter?

2 posts were merged into an existing topic: What are the backslashes in the string?

2 posts were split to a new topic: What’s wrong with my code?

3 posts were split to a new topic: What are good reasons to use string formatting?

3 posts were merged into an existing topic: Why does the order of the arguments matter?

Hi, I don’t understand why this doesn’t go through it seems fine?

def poem_title_card(poet, title):
  return "The poem \"{}\" is written by {}".format(title, poet)

print(poem_title_card("Walt Whitman", "I Hear America Singing"))

Expected poem_title_card("Walt Whitman", "I Hear America Singing") to return "The poem "I Hear America Singing" is written by Walt Whitman." , but instead got "The poem "I Hear America Singing" is written by Walt Whitman" . Check your spelling and punctuation.

Looks the same to me, what gives?

Looks the same?
Is the same, or sorta looks the same at a glance?

So I was missing the . at the end… :man_facepalming:

Quick Question about why the escaping can’t be done from within the {}, is it because it doesn’t exactly match the argument given?

The solution was:

def poem_title_card(poet, title):
  poem_desc = "The poem \"{}\" is written by {}.".format(title, poet)
  return poem_desc

Why can’t the backlashes be inside of the {} like so:

def poem_title_card(poet, title):
  poem_desc = "The poem {\" \"} is written by {}.".format(title, poet)
  return poem_desc
1 Like

The curly braces (replacement field) serve a particular purpose where they take the name referencing an object and return a string formatted version of it (e.g the string character ‘3’ for an int object with the value of 3).

The syntax for this field is very limited, see the documentation for example-
https://docs.python.org/3/library/string.html#format-string-syntax

That is very helpful, thank you~