String formatting
programming
coding
Python
Java

How to create a String with format?

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

Creating a formatted string means building text from values such as names, numbers, dates, or computed expressions. The exact syntax depends on the language, but the underlying goal is the same: insert dynamic values into a readable template without manual concatenation everywhere. Good formatting code is easier to read, less error-prone, and usually easier to localize later.

Why Formatting Is Better Than Manual Concatenation

You can always build strings with +, but that becomes messy once formatting rules matter.

For example, this style gets awkward quickly:

python
1name = "Alice"
2age = 30
3message = "User " + name + " is " + str(age) + " years old"
4print(message)

A formatting API makes the structure clearer and handles type conversion more naturally.

Python Examples

Modern Python usually uses f-strings.

python
1name = "Alice"
2age = 30
3score = 91.234
4
5message = f"User {name} is {age} years old and scored {score:.1f}"
6print(message)

Output:

text
User Alice is 30 years old and scored 91.2

You can also use str.format() if you need a reusable template.

python
template = "User {name} is {age} years old"
message = template.format(name="Alice", age=30)
print(message)

F-strings are usually the most readable when the values are already in local variables.

Java Examples

In Java, the standard option is String.format().

java
1public class Main {
2    public static void main(String[] args) {
3        String name = "Bob";
4        int age = 28;
5        double score = 91.234;
6
7        String message = String.format(
8            "User %s is %d years old and scored %.1f",
9            name,
10            age,
11            score
12        );
13
14        System.out.println(message);
15    }
16}

The placeholders use format specifiers:

  • '%s for strings'
  • '%d for integers'
  • '%f for floating-point numbers'

So %.1f means "show one digit after the decimal point."

JavaScript Examples

JavaScript does not have a direct equivalent to String.format() in the language core, but template literals are the standard solution.

javascript
1const name = "Charlie";
2const age = 25;
3const score = 91.234;
4
5const message = `User ${name} is ${age} years old and scored ${score.toFixed(1)}`;
6console.log(message);

Template literals are also convenient for multi-line text.

javascript
const block = `Name: ${name}
Age: ${age}`;
console.log(block);

Formatting Rules Matter Too

Formatting is not only about inserting values. It is also about how those values should look.

Examples include:

  • limiting decimal places
  • left or right alignment
  • zero padding
  • date or currency formatting

A simple Python example with alignment:

python
item = "CPU"
price = 7.5
print(f"{item:<10} ${price:>6.2f}")

A comparable Java example:

java
System.out.println(String.format("%-10s $%6.2f", "CPU", 7.5));

Once you start formatting tables, logs, or reports, these details matter a lot.

Reusable Templates Are Often Better

If the same text pattern appears in several places, keep the format in one template instead of rebuilding it repeatedly. That makes later edits easier and reduces subtle formatting drift across the codebase.

This matters especially for logs, CLI output, and user-facing messages where consistency is part of maintainability.

Common Pitfalls

  • Using manual concatenation for complex templates and making the code hard to read.
  • Forgetting numeric format specifiers such as decimal precision.
  • Mixing placeholder styles incorrectly, especially when switching between languages.
  • Building user-facing messages inline everywhere instead of keeping reusable templates.
  • Assuming formatting automatically handles localization for dates, numbers, or currency.

Summary

  • Formatted strings are cleaner than repeated concatenation.
  • Python commonly uses f-strings or str.format().
  • Java commonly uses String.format() with format specifiers.
  • JavaScript commonly uses template literals.
  • Good string formatting is about both inserting values and controlling how those values are displayed.

Course illustration
Course illustration

All Rights Reserved.