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 specify where the values should be substituted, and the arguments passed to the function are inserted in order at the specified locations.
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 dynamic strings, where the string may change based on variables, etc.
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"])
Guidelines
AI Tutor
Publish
Design
Upload
Notes
Favorites
Help
Code Editor
Execution Result