A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.geeksforgeeks.org/python/python-insert-a-number-in-string/ below:

Insert a number in string - Python

Insert a number in string - Python

Last Updated : 12 Jul, 2025

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:

Using f-Strings

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)

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)

Explanation:

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)

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)

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.



RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4