The format() function is commonly used in various programming languages to format strings. Below are examples of how it works in Python and JavaScript:
Python
In Python, format() is a method of string objects that allows you to format strings by inserting values into placeholders defined by curly braces {}.
Example:
name = "Alice"
age = 30
formatted_string = "My name is {} and I am {} years old.".format(name, age)
print(formatted_string)
Output:
My name is Alice and I am 30 years old.
You can also use indexed placeholders:
formatted_string = "My name is {0} and I am {1} years old. {0} is great!".format(name, age)
print(formatted_string)
JavaScript
In JavaScript, format() is not a built-in function for strings, but you can achieve similar functionality using template literals or by creating your own formatting function.
Using Template Literals:
const name = "Alice";
const age = 30;
const formattedString = `My name is ${name} and I am ${age} years old.`;
console.log(formattedString);
Output:
My name is Alice and I am 30 years old.
If you want to create a custom format function, you can do something like this:
function format(template, ...values) {
return template.replace(/{(\d+)}/g, (match, index) => values[index]);
}
const name = "Alice";
const age = 30;
const formattedString = format("My name is {0} and I am {1} years old.", name, age);
console.log(formattedString);
Output:
My name is Alice and I am 30 years old.
Feel free to ask if you need more specific examples or details!
