A string is a sequence of characters used to represent text. Names, messages, and user input are all stored as strings.
For a broader introduction to data types including strings, see Data Types.
Creating a String#
A string is written between quotation marks.
string name = "Odds and Evens";name = "Odds and Evens"let name = "Odds and Evens";String Interpolation#
String interpolation lets you embed the value of a variable directly inside a string. Instead of building the string in pieces, you write the whole message in one place with placeholders for the variable values.
int score = 10;
Console.WriteLine($"Your score is {score}.");Place a $ before the opening quote to mark the string as interpolated. Any variable name inside {} is replaced with its value when the program runs. The output is Your score is 10.
score = 10
print(f"Your score is {score}.")Place an f before the opening quote to mark the string as an f-string. Any variable name inside {} is replaced with its value when the program runs. The output is Your score is 10.
let score = 10;
console.log(`Your score is ${score}.`);Use backticks instead of quotes to mark the string as a template literal. Any variable name inside ${} is replaced with its value when the program runs. The output is Your score is 10.
Common Mistakes#
Forgetting the interpolation prefix
Without the $ in C#, the f in Python, or the backticks in JavaScript, the curly braces are treated as plain text. The output will print {score} literally instead of the actual value.
Putting quotes inside the curly braces
Writing {"score"} instead of {score} prints the variable name as text rather than its value. Variable names inside {} need no quotes.
Mixing up quote types in JavaScript
Template literals use backticks `, not regular quotes. Writing "Your score is ${score}." with regular quotes prints the ${} literally instead of interpolating the value.
Confusing string concatenation with interpolation
Writing "Your score is " + score works in most languages but is more error-prone and harder to read than interpolation, especially with multiple variables. Prefer interpolation when it’s available.
Forgetting the closing quote A string that starts with a quote must end with a matching quote. A missing closing quote causes a syntax error.