How to add a variable to a string in Python
Learn how to add a variable to a string in Python. Explore different methods, tips, real-world applications, and common error debugging.

In Python, you often need to combine variables with strings for dynamic text. This fundamental skill is essential for simple print statements, complex data formats, and user outputs.
In this article, you'll learn several techniques to insert variables into strings. You'll also find practical tips, real-world applications, and advice to help you debug common issues.
Using the + operator for string concatenation
name = "Alice"
greeting = "Hello, " + name + "!"
print(greeting)--OUTPUT--Hello, Alice!
The + operator offers a straightforward way to perform string concatenation. It works by linking strings together in the order you specify. The example demonstrates how you can chain these operations, joining the literal string "Hello, " with the name variable and the final "!".
- Simplicity: It's intuitive and easy to read for basic combinations.
- Type Specificity: A key thing to remember is that the
+operator is strict. It only works between strings. Attempting to add a number or another type directly will result in aTypeError, so you'd have to convert them first.
Basic string formatting techniques
While the + operator is simple, Python offers more powerful and flexible methods for handling different data types without needing manual conversion.
Using the % operator for string formatting
age = 30
message = "I am %d years old." % age
print(message)--OUTPUT--I am 30 years old.
The % operator, an older method borrowed from C, lets you format strings by inserting variables into placeholders. In the example, %d is a format specifier that marks the spot for a decimal integer. The operator then replaces this specifier with the value of the age variable.
- Type Handling: It automatically converts numbers to strings, so you don't need to use
str(). - Flexibility: You can use different specifiers like
%sfor strings or%ffor floating-point numbers.
Using the .format() method
city = "New York"
population = 8.4
info = "{} has approximately {:.1f} million people.".format(city, population)
print(info)--OUTPUT--New York has approximately 8.4 million people.
The .format() method offers a more modern and readable way to insert variables into strings. It uses curly braces {} as placeholders, which are then filled by the variables you pass to the method. In the example, {} is replaced by the city variable, while {:.1f} formats the population as a float with one decimal place.
- Readability: It separates the string from the variables, which can make complex statements easier to read.
- Powerful Formatting: You get fine-grained control over how variables are displayed without changing the variables themselves.
Using f-strings for direct variable insertion
name = "Bob"
age = 25
introduction = f"My name is {name} and I am {age} years old."
print(introduction)--OUTPUT--My name is Bob and I am 25 years old.
F-strings, or formatted string literals, offer a modern and highly readable way to embed variables. You simply prefix the string with an f and place your variables or expressions inside curly braces {}. In the example, name and age are inserted directly, making the code's intent clear at a glance.
- Conciseness: The syntax is clean because the variables are right where they'll appear in the output.
- Performance: They are evaluated at runtime and are generally the fastest formatting method in Python.
Advanced string formatting techniques
Beyond the everyday methods, Python offers specialized tools for when you need secure substitutions, precise alignment, or different numeric representations in your strings.
Using template strings from the string module
from string import Template
language = "Python"
t = Template("I love coding in $lang!")
result = t.substitute(lang=language)
print(result)--OUTPUT--I love coding in Python!
Template strings from Python's string module offer a secure way to handle substitutions, especially with user-generated text. Unlike other methods, they don't execute expressions, which makes them safer. The syntax is simple—it uses a dollar sign ($) to mark placeholders like $lang.
- Security-focused: Their main advantage is preventing unintended code execution, making them ideal for templates that might come from external sources.
- Object-oriented: You first create a
Templateobject, then call thesubstitute()method to fill in the values.
Formatting with alignment and padding
products = ["Apple", "Banana", "Orange"]
prices = [1.20, 0.50, 0.80]
for product, price in zip(products, prices):
print(f"{product:10} | ${price:5.2f}")--OUTPUT--Apple | $ 1.20
Banana | $ 0.50
Orange | $ 0.80
F-strings give you precise control over text alignment and padding, which is perfect for creating clean, table-like outputs. The code aligns product names and prices into columns by specifying the total space each value should occupy.
- For the
productvariable,:10reserves 10 character spaces. Since it's a string, it's automatically left-aligned. - For the
pricevariable,:5.2fformats the number. It allocates a total width of 5 characters, rounds the value to two decimal places using.2f, and right-aligns the result.
Converting variables to different number formats
num = 42
binary = f"{num:b}"
octal = f"{num:o}"
hexadecimal = f"{num:x}"
print(f"Decimal: {num}, Binary: {binary}, Octal: {octal}, Hex: {hexadecimal}")--OUTPUT--Decimal: 42, Binary: 101010, Octal: 52, Hex: 2a
F-strings aren't just for text alignment; they can also convert numbers into different bases. This is useful for tasks like low-level programming or data representation. The code shows how to take an integer, num, and display it in several common formats.
:bconverts the number to its binary (base-2) equivalent.:oconverts it to octal (base-8).:xconverts it to hexadecimal (base-16).
This built-in feature saves you from writing manual conversion functions, making it a clean and direct way to handle different numeral systems.
Move faster with Replit
Replit is an AI-powered development platform that transforms natural language into working applications. You can describe what you want to build, and its AI capabilities will help bring your idea to life, from initial code to full deployment.
The string formatting techniques you've just learned are the building blocks for real-world tools. With Replit Agent, you can turn these concepts into complete applications—including databases, APIs, and deployment—simply by describing your goal.
- Build a command-line tool that generates neatly formatted sales receipts, using f-string padding to align product names and prices in clean columns.
- Create a number base converter that takes a decimal input and displays its binary, octal, and hexadecimal equivalents, using the
:b,:o, and:xformat specifiers. - Deploy a personalized notification system that uses template strings to safely insert user data like names and appointment times into automated messages.
Turn your concept into a functional app. Describe your idea and let Replit Agent write, test, and deploy the code for you.
Common errors and challenges
Even with the right tools, you can run into a few common snags when inserting variables into strings.
When using the + operator, you might encounter a TypeError. This error happens because Python is strict about types and won't automatically convert a number or other object into a string during concatenation. You can easily fix this by manually converting your variable with the str() function before you join it to the string.
A frequent slip-up with f-strings is forgetting to place the f before the opening quote. If the prefix is missing, Python won't evaluate the expressions inside the curly braces {}. Instead, it will treat them as literal text, so your output will include the braces and variable name instead of the variable's value.
With the .format() method, you may see an IndexError if the number of placeholders doesn't match the number of arguments you pass to the method. To avoid this, ensure there's a one-to-one correspondence between the curly braces {} in your string and the variables you provide.
Fixing type errors when using the + operator for concatenation
A common hurdle when using the + operator is the TypeError. This error appears because Python won't automatically convert non-string types, like numbers, during concatenation. The code below demonstrates what happens when you attempt to add an integer directly to a string.
age = 30
message = "I am " + age + " years old."
print(message)
This code triggers a TypeError because the + operator is trying to combine a string with an integer. Python doesn't automatically convert the number for you. The following example shows the correct approach to fix it.
age = 30
message = "I am " + str(age) + " years old."
print(message)
The solution is to wrap the non-string variable in the str() function. By calling str(age), you explicitly convert the integer into its string form before the operation. This allows the + operator to successfully join all the parts without raising a TypeError. Keep an eye out for this whenever you're building strings that mix text with numbers or other data types, as Python requires manual conversion for concatenation.
Handling missing curly braces in f-strings
Forgetting to wrap a variable in curly braces {} is a frequent f-string slip-up. When the braces are missing, Python doesn't replace the variable with its value and instead treats its name as plain text. The code below demonstrates this common error.
name = "Charlie"
greeting = f"Hello, name!"
print(greeting)
The output is Hello, name! because the f-string doesn't know to replace the word name with its value. It's treated as literal text. The corrected code below shows how to signal the substitution.
name = "Charlie"
greeting = f"Hello, {name}!"
print(greeting)
The solution is to enclose the variable in curly braces, like f"Hello, {name}!". These braces are the key—they tell Python to replace the variable name with its actual value. Without them, the f-string sees name as literal text. It's an easy mistake to make when you're coding fast, so be sure to check that all your variables are correctly wrapped to ensure they're evaluated properly.
Correcting format specifier errors in the .format() method
With the .format() method, you can get a ValueError if a format specifier doesn't align with the variable's data type. You can't, for instance, format text as a number. The code below demonstrates what happens when these types are mismatched.
price = 49.95
product = "Headphones"
output = "{} costs {:.2f}".format(price, product)
print(output)
This code triggers a ValueError because the arguments passed to .format() are out of order. The string product is incorrectly paired with the float specifier :.2f, which it cannot process. The corrected code below shows the proper order.
price = 49.95
product = "Headphones"
output = "{} costs {:.2f}".format(product, price)
print(output)
The solution is to match the order of your variables with their corresponding placeholders. The code fails because it’s trying to format the product string with :.2f, a specifier meant for floats. By passing product first and price second to .format(), you align each variable with its correct placeholder. Keep an eye on this when using multiple format specifiers, as a simple mix-up in order can cause a ValueError.
Real-world applications
Beyond the syntax and error handling, these string formatting techniques are fundamental to many practical, everyday programming tasks.
Creating dynamic file names with f-strings
F-strings make it simple to generate unique and descriptive filenames on the fly by combining static text with variables like a user ID and the current date.
from datetime import datetime
current_date = datetime.now()
user_id = "user123"
filename = f"report_{user_id}_{current_date.strftime('%Y-%m-%d')}.csv"
print(f"File saved as: {filename}")
This example highlights a key strength of f-strings: evaluating expressions in place. Instead of just inserting a variable, the code executes the current_date.strftime('%Y-%m-%d') method call directly within the string.
- The
strftime()method formats the date object into a clean, sortableYYYY-MM-DDstring. - This allows you to create complex, dynamic strings without needing intermediate variables, making your code more concise for tasks like generating unique report names or log files.
Formatting log entries with alignment and timestamps
You can use f-strings to create well-structured log messages, combining formatted timestamps with padded text to ensure every entry is perfectly aligned and easy to scan.
from datetime import datetime
def log_event(severity, message):
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
severity_formatted = f"[{severity.upper():7}]"
print(f"{timestamp} {severity_formatted} - {message}")
log_event("info", "Application started")
log_event("warning", "Low disk space detected")
log_event("error", "Connection failed to database")
This log_event function demonstrates a practical way to create structured log messages. It combines dynamic data—a current timestamp—with input arguments like severity and message. The function processes these pieces and assembles them into a single, consistently formatted string for output.
- This approach encapsulates logging logic, so you can call
log_eventfrom anywhere without rewriting formatting code. - It's a common pattern for ensuring all events, from routine info to critical errors, are recorded in a uniform and readable way.
Get started with Replit
Put your knowledge into practice with Replit Agent. Describe what you want to build, like “a receipt generator with aligned columns” or “a tool that converts numbers to binary and hex.”
The AI will write the code, test for errors, and deploy your application for you. Start building with Replit.
Create and deploy websites, automations, internal tools, data pipelines and more in any programming language without setup, downloads or extra tools. All in a single cloud workspace with AI built in.
Create & deploy websites, automations, internal tools, data pipelines and more in any programming language without setup, downloads or extra tools. All in a single cloud workspace with AI built in.


.png)
.png)