Python String - Append Number


Python String - Append Number

To append a number to a string in Python, you can use string concatenation or formatted strings.

In this tutorial, we shall go through these two approaches, and learn how to append a number to a string with examples.

1. Append number to string using string concatenation and str() in Python

Given a string in x and a number in n. We have to append the number in n to the string in x using string concatenation operator and str() built-in function.

Steps

  1. Given string in x, and number in n.
x = "apple"
n = 123
  1. Convert number in n to a string using str() built-in function. Python str() built-in function can take a number, and return a string created from the given number.
str(n)
  1. Use string concatenation operator + and concatenate the string in x, and the string created from n using str(n).
x + str(n)

The above expression returns a new string, where the number n is appended to the string in x. You may use it as per your requirement, but here, we shall just print it to the standard output.

Program

The complete program to append a number to a string in Python using string concatenation operator and str() built-in function.

Python Program

# Given string
x = "apple"

# Given number
n = 123

# Append the number to the string
result = x + str(n)

# Print the result
print(result)

Output

apple123

2. Append number to string using formatted strings in Python

Given a string in x and a number in n. We have to append the number in n to the string in x using formatted strings.

Steps

  1. Given string in x, and number in n.
x = "apple"
n = 123
  1. Create a new formatted string with the string x and the number n specified next to each other, as shown in the following.
f"{x}{n}"

The above expression returns a new string, where the number n is appended to the string in x.

Program

The complete program to append a number to a string in Python using formatted strings.

Python Program

# Given string
x = "apple"

# Given number
n = 123

# Append the number to the string
result = f"{x}{n}"

# Print the result
print(result)

Output

apple123

Summary

In this Python Strings tutorial, we learned how to append a number to a string. In the first approach, we used string concatenation operator along with the str() built-in function. In the second approach, we used formatted strings. We have covered programs for each of these approaches.