How to Print a Variable Inside String in Python

Here are four ways to print a variable inside a string in Python:

  1. Using f-string
  2. Using the format() function with print() function
  3. Using concatenation to print a variable inside a string
  4. Using the % sign

Method 1: Using f-string

The f-string is a way of formatting strings using embedded Python expressions inside string constants. The f-string is new to Python 3.

Python Formatted string literals are parser features that convert f-strings into a series of string constants and expressions. Ultimately, they all combine to build the final string, which we can print in the console.

exchange = "FTX"

print(f"Sorry to say that {exchange} has filed for bankruptcy!")

Output

Sorry to say that FTX has filed bankruptcy!

Method 2: Using format() function with print() function

To print a variable inside a string in Python, you can use the “format()” function inside the “print()” function. The format() function formats the provided values and adds them inside the placeholder of a string. The print() function prints the defined text to the console.

exchange = "FTX"

print("Sorry to say that {} has filed for bankruptcy!".format(exchange))

Output

Sorry to say that FTX has filed for bankruptcy!

Method 3: Using concatenation to print a variable inside a string

The concatenate operator (+) helps us put a variable inside a print() function and prints it in the console.

Remember that the concatenation approach can only be used for strings, so if the variable you need to concatenate with the rest of the strings is an integer, convert it first from an integer to a string using the str() function.

exchange = "FTX"

print("Sorry to say that " + exchange + " has filed for bankruptcy!")

Output

Sorry to say that FTX has filed for bankruptcy!

Method 4: Using % sign

exchange = "FTX"

print("Sorry to say that %s has filed for bankruptcy!" %exchange)

Output

Sorry to say that FTX has filed for bankruptcy!

How to print multiple variables inside a string in Python

To print multiple variables inside a string, you can use the “f-string” in Python. The f-string can help us print the value of multiple variables in the console.

exchange = "FTX"
culprit = "Sam bankman fried"

print(f"Due to {culprit}, {exchange} has filed for bankruptcy!")

Output

Due to Sam bankman fried, FTX has filed for bankruptcy!

That’s it.

Related posts

Print no newline in Python

Python print line break

How to print bold text

Leave a Comment

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