How To Use Variables in a Python String

Using variables in a string is a common operation in programming. In Python, there are several ways to include variables in a string.

This blog post will give you 3 options to help you use variables within a string and print.

Format

In Python, you can use variables in strings by using the format() method. Below we have two variables that we will use in the examples below.

name = 'John'
age = 30

Use the format() method to insert the variables into the string

greeting = 'Hello, my name is {}, and I am {} years old'.format(name, age)

Output:

"Hello, my name is John, and I am 30 years old"

F-Strings

You can also use the f-strings feature introduced in Python 3.6 to embed expressions inside string literals using the f prefix and curly braces. Here’s the same example using f-strings:

name = 'John'
age = 30

Use f-strings to embed the variables in the string

greeting = f'Hello, my name is {name}, and I am {age} years old'

Output:

 "Hello, my name is John, and I am 30 years old"

You can also use the % operator to format strings like this:

name = 'John'
age = 30

% Operator

Use the % operator to format the string. The %s operator prints a string, and the %d operator prints an integer.

greeting = 'Hello, my name is %s, and I am %d years old' %(name, age)

Output:

"Hello, my name is John, and I am 30 years old"

Processing…
Success! You're on the list.


Posted

in

by

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.