Python String - Append Variable


Python String - Append Variable

To append the value in a variable to a string in Python, you can use string concatenation with str() built-in function, or formatted strings.

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

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

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

Steps

  1. Given string in my_string, and variable in x.
my_string = "apple"
x = 3.14
  1. Convert value in variable x to a string using str() built-in function. Python str() built-in function can take a value, and return a string representation of it.
str(x)
  1. Use string concatenation operator + and concatenate the string in my_string, and the string created from x using str(x).
my_string + str(x)

The above expression returns a new string, where the value in variable x is appended to the string my_string. 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 variable to a string in Python using string concatenation operator and str() built-in function.

Python Program

# Given string
my_string = "apple"

# Given variable
x = 3.14

# Append the variable to the string
result = my_string + str(x)

# Print the result
print(result)

Output

apple3.14

2. Append variable to the string using formatted strings in Python

Given a string in my_string and variable in x. We have to append the variable x to the string in my_string using formatted strings.

Steps

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

The above expression returns a new string, where the variable x is appended to the string my_string.

Program

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

Python Program

# Given string
my_string = "apple"

# Given variable
x = 3.14

# Append the variable to the string
result = f"{my_string}{x}"

# Print the result
print(result)

Output

apple3.14

Summary

In this Python Strings tutorial, we learned how to append a variable 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.