Python – Create String from Two Variables

Python – Create String from Two Variables

To create a string from two variables in Python, you can use formatted string.

In this tutorial, we shall go through some examples on how you can take two variables, and create a string from these two variables, in Python.

Create string from two variables using formatted string in Python

Given two variables are x and y.

Using a formatted string, and placing the variables x and y in that formatted string implicitly converts the value in variable x and y to strings, and creates a new string.

The format of the string depends on your requirement.

For example, let us say that variable x holds total spends, and variable y holds total credits, and we would like to print to the user about the summary of his transactions in a format as shown in the following example.

Python Program

# Given variables
x = 1234
y = 5072

# Formatted string
result = f"Summary\nTotal earnings : ${y}\nTotal spends : ${x}"

# Print resulting string
print(result)
Run Code Copy

Output

Summary
Total earnings : $5072
Total spends : $1234

Now, let us take another example, where we are given the name and age of a student, and we need to print these details in a string in a specific format.

Python Program

# Given variables
name = "Apple"
age = 12

# Formatted string
result = f"Name is {name}, and age is {age}."

# Print resulting string
print(result)
Run Code Copy

Output

Name is Apple, and age is 12.

Summary

In this Python strings tutorial, we learned how to create a string from given two variables using formatted strings.

Related Tutorials

Code copied to clipboard successfully 👍