Inserting Variables into Strings with the format() Function
The format()
function is used to insert variables or values into a string.
The format function uses curly braces { }
within the string to indicate where values should be inserted. The arguments passed to the function are placed in the specified locations in the order they appear.
greeting = "Hello, {0}! Today is {1}." formatted_greeting = greeting.format("CodeFriend", "Tuesday") print(formatted_greeting) # "Hello, CodeFriend! Today is Tuesday."
The format() function is useful for creating dynamic strings, allowing the content to change based on variables and other input.
What is the correct way to insert variables into a string using the format() function?
"Hello, {0}! Today is {1}.".format("CodeFriend", "Tuesday")
"Hello, {name}! Today is {day}.".format("CodeFriend", "Tuesday")
"Hello, CodeFriend! Today is Tuesday.".format()
"Hello, {0}! Today is {1}.".format(["CodeFriend", "Tuesday"])
Lecture
AI Tutor
Publish
Design
Upload
Notes
Favorites
Help
Code Editor
Execution Result