Python Format String
String formatting in Python allows you to create dynamic strings by embedding variables and expressions within a string. This is useful for creating formatted output, building messages, and more.
Using f-Strings
f-Strings, introduced in Python 3.6, provide a concise and readable way to format strings. You can include variables and expressions inside curly braces {}
within an f-string. For example:
const name = 'Alice';
const age = 30;
const formattedString = `My name is ${name} and I am ${age} years old.`;
The {}
inside the curly braces is replaced with the value of the variable or expression. In this case, {name}
is replaced with Alice
and {age}
is replaced with 30
.
Formatting Expressions
You can also format expressions inside an f-string. For example, you can format numbers to a specific number of decimal places using {expression:.2f}
to format as a float with 2 decimal places.
Conclusion
String formatting in Python using f-strings provides a powerful and flexible way to create dynamic strings. By embedding variables and expressions within a string, you can easily create formatted output tailored to your needs.