Open In App

Insert a number in string - Python

Last Updated : 12 Jul, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

We are given a string and a number, and our task is to insert the number into the string. This can be useful when generating dynamic messages, formatting output, or constructing data strings. For example, if we have a number like 42 and a string like "The number is", then the output will be "The number is 42". Let's explore some common and efficient methods of doing it with examples:

Introduced in Python 3.6, f-strings offer a fast and readable way to embed variables directly into strings. They’re evaluated at runtime and are considered the most efficient method.

Python
n = 42

res = f"The number is {n}"

print(res)

Output
The number is 42

Explanation: The f before the string allows expressions inside {} to be evaluated. It’s concise, readable, and performs faster than older methods.

Using String Concatenation

This is the most basic method where we convert the number to a string and join it with the original string using the + operator.

Python
s = "The number is "
n = 42

res = s + str(n)

print(res)

Output
The number is 42

Explanation:

  • str(n) converts the integer n to a string, allowing it to be concatenated with the original string s.
  • + operator is used to concatenate the two strings, resulting in the combined string.

Using String Formatting (% operator)

It's a classical method that uses format specifiers like %d for integers, allowing the insertion of numbers at specific placeholders.

Python
s = "The number is %d"
n = 42

res = s % n

print(res)

Output
The number is 42

Explanation: %d in the string acts as a placeholder for an integer, which is replaced with the value of num.

Using str.format() Method

This method allows us to insert variables into a string by placing curly braces {} as placeholders. This method offers greater flexibility and readability compared to older formatting methods like % operator, supporting both positional and keyword arguments

Python
s = "The number is {}"
n = 42

res = s.format(n)

print(res)

Output
The number is 42

Explanation: Curly braces {} serve as placeholders, and format(num) replaces them with the number, resulting in a clean and formatted string.

Also read: str.format(), f-strings.


Practice Tags :

Similar Reads

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy