Insert a number in string Python (original) (raw)
Last Updated : 22 Apr, 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:
- **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)
`
**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.