String Interpolation - chrisbitm/python GitHub Wiki
String interpolation is a feature in that allows you to embed expressions within String literals. This makes it easier to construct dynamic strings without the need for concatenation, improving both readability and maintainability of your code.
s-Interpolator
The s-interpolator allows you to embed variable values and expressions directly into a String.
Example 1
val name: String = "Yoda";
val age: Short = 900;
print(s"My name is $name and I am $age years old.");
My name is Yoda and I am 900 years old
- Notice a
$
next to the Variablesname
andage
in theprint
statement
Example 2
println(s"100 times 3 = ${100 * 3}")
100 times 3 = 300
- It also works to Output Arithmetic Expression. Do not forget to enclose the Expression inside
{}
Example 3
println(s"This book costs $$12.55!")
This book costs $12.55!
- If you want to display Currency with a Dollar Sybol. You must use a double
$$
due to the Character being a delimiter.
var name: String = "Yoda";
var age: Short = 900;
val str1: String = "Game Over for you!";
println(s"My Name is $name and I am $age years old.");
print(s"$str1");
My Name is Yoda and I am 900 years old.
Game Over for you!
f-Interpolator
The f-interpolator is used for creating formatted strings. It allows you to embed expressions within string literals and format them in a way that's similar to printf
. This is particularly useful when you need precise control over the output format of numbers, dates, and other datatypes.
val name = "Alice";
val bookCost = 877.99;
val pocket = 1300.5F;
val age = 900;
println(f"My name is $name%s take liking a book costing $bookCost%.2f");
println(f"$name%s has enough in pocket. $pocket%s can cover");
println(f"About Yoda man who is $age%d years old");
My name is Alice take liking a book costing 877.99
Alice has enough in pocket. 1300 can cover
val name = "Alice";
val bookCost = 877.99;
val pocket = 1300.5F;
val age = 900;
println(f"My name is $name%s take liking a book costing $bookCost%.2f");
println(f"$name%s has enough in pocket. $pocket%.2f can cover");
println(f"About Yoda man who is $age%d years old.");
My name is Alice take liking a book costing 877.99
Alice has enough in pocket. 1300.50 can cover
About Yoda man who is 900 years old.
%s
is used to format strings%.2f
is used to format Floating-Point Numbers to two decimal places.%d
is used to format a digit as is.