Python - Create String from Variable


Python - Create String from Variable

To create a string from a variable in Python, you can use str() built-in function or use the variable in a formatted string.

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

1. Create string from variable using str() in Python

Given variable in x.

Call str() built-in function and pass the given variable as argument. The function returns a string value created using the given variable. Whatever the type of value in x, the str() built-in function returns the string representation of the value in the variable.

Python Program

# Given variable
x = 3.14896

# Convert variable to string
result = str(x)

# Print resulting string
print("String : " + result)

Output

String : 3.14896

The fact that we could concatenate the result with "String : " in the print() statement proves that the result is a string value.

Let us try with a different type of value in variable x, say a list.

Python Program

# Given variable
x = ["apple", "banana", "cherry"]

# Convert variable to string
result = str(x)

# Print resulting string
print("String : " + result)

Output

String : ['apple', 'banana', 'cherry']

The list has been converted to string.

2. Create string from variable using formatted string in Python

Given variable in x.

Using a formatted string, and placing the variable x in that formatted string, implicitly converts the value in variable x to a string value.

For example, in the following program, we use variable x in a formatted string.

Python Program

# Given variable
x = 1234

# Convert variable to string in formatted string
result = f"Account Balance : ${x}"

# Print resulting string
print(result)

Output

Account Balance : $1234

Summary

In this Python strings tutorial, we learned how to create a string from a given variable using str() built-in function or formatted strings.