How to print a string and int in Python

Discover various ways to print strings and integers in Python. Get tips, see real-world applications, and learn to debug common errors.

How to print a string and int in Python
Published on: 
Mon
Apr 6, 2026
Updated on: 
Fri
Apr 10, 2026
The Replit Team

The ability to print strings and integers is a fundamental Python skill. You'll use the print() function to display output, which is essential for tasks like code debugging.

In this article, you'll explore various techniques to print combined strings and integers. You'll also find practical tips, see real-world applications, and get advice for debugging common print-related errors.

Basic printing with print()

print("Hello, World!") # Printing a string
print(42) # Printing an integer
print("The answer is", 42) # Printing string and integer together--OUTPUT--Hello, World!
42
The answer is 42

The print() function can handle multiple arguments. The final line, print("The answer is", 42), is a straightforward way to display mixed data types. When you pass comma-separated arguments to print(), it does a couple of things automatically:

  • It converts each non-string argument, like the integer 42, into its string representation.
  • It inserts a single space between each argument by default.

This makes it a handy shortcut for quick output without needing manual string formatting.

Basic string and integer printing techniques

While the basic print() function is useful, you'll gain more control over your output by explicitly formatting strings with integers before printing them.

Using f-strings for combining strings and integers

name = "Python"
version = 3.9
print(f"I'm using {name} version {version}")
print(f"The result of 5 + 10 is {5 + 10}")--OUTPUT--I'm using Python version 3.9
The result of 5 + 10 is 15

F-strings, or formatted string literals, are a modern and readable way to embed Python expressions inside strings. You create one by prefixing the string with an f and placing your variables or expressions inside curly braces {}.

  • Python evaluates the code inside the braces, letting you embed variables like {name}.
  • You can also perform calculations on the fly, like {5 + 10}, directly within the string.

This approach is often preferred for its clarity and performance, making your code much cleaner.

Converting integers to strings with str()

age = 25
print("I am " + str(age) + " years old")
print(str(42) + " is the answer")--OUTPUT--I am 25 years old
42 is the answer

Another way to combine strings and integers is by manually converting the integer to a string using the str() function. Python doesn't allow you to add a string and an integer together with the + operator—it will result in a TypeError. By wrapping the integer in str(), you turn it into a string first, allowing for concatenation.

  • This approach gives you precise control over the output. Unlike passing comma-separated arguments to print(), you must add your own spaces when concatenating, as in "I am " + str(age) + " years old".

Using the + operator with type conversion

count = 10
message = "You have " + str(count) + " notifications"
print(message)
print("Score: " + str(95) + "/100")--OUTPUT--You have 10 notifications
Score: 95/100

This technique is useful for creating a new string variable before you print it. You use the + operator to join strings together, a process known as concatenation. Since you can't add a string to an integer, you must first convert the integer using str().

  • In the example, the message variable stores the complete string before it's passed to print().
  • Building a string this way is ideal when you need to reuse the formatted text elsewhere in your code, not just display it once.

Advanced string and integer printing techniques

While f-strings are a modern favorite, older techniques like the .format() method and the % operator offer powerful ways to specify your output format.

Formatting with the .format() method

name = "Alice"
age = 30
print("Hello, my name is {} and I am {} years old.".format(name, age))
print("The value of pi is approximately {:.2f}".format(3.14159))--OUTPUT--Hello, my name is Alice and I am 30 years old.
The value of pi is approximately 3.14

The .format() method is a versatile way to build strings. You place curly brace placeholders {} in your string and then call the method, passing the variables you want to insert.

  • The arguments are inserted in order. In the example, name fills the first placeholder and age fills the second.
  • You can also control the formatting. The specifier :.2f inside a placeholder tells Python to format the number as a float with two decimal places, which is great for controlling numerical output.

Using string formatting with the % operator

quantity = 3
item = "apples"
price = 0.5
print("I bought %d %s for $%.2f each" % (quantity, item, price))
print("The year is %d and the temperature is %d degrees" % (2023, 25))--OUTPUT--I bought 3 apples for $0.50 each
The year is 2023 and the temperature is 25 degrees

The % operator is one of Python's original string formatting methods. It works by placing special format specifiers inside your string, which act as placeholders for your variables. The values you want to insert are then passed in a tuple after the % operator.

  • Placeholders like %d are for integers, while %s is for strings.
  • You can also control formatting. For example, %.2f formats a number as a float with two decimal places.
  • The order of the variables in the tuple must match the order of the placeholders in the string.

Advanced formatting with specification

num = 42
print(f"{num:05d}") # Zero-padded to 5 digits
print(f"Binary: {num:b}, Hexadecimal: {num:x}, Octal: {num:o}")--OUTPUT--00042
Binary: 101010, Hexadecimal: 2a, Octal: 52

F-strings let you add format specifiers after a colon (:) for more advanced output. For example, {num:05d} pads the integer with leading zeros to ensure it's five digits wide. This is perfect for aligning numbers or creating standardized identifiers.

  • You can also convert numbers to different bases directly within the string.
  • Use :b to get the binary representation.
  • Use :x for hexadecimal.
  • Use :o for octal.

Move faster with Replit

Replit is an AI-powered development platform where you can skip setup and start coding Python instantly. All the necessary dependencies come pre-installed, so you don't have to worry about environment configuration.

With Agent 4, you can move from learning individual techniques to building complete applications. Instead of piecing code together, describe the app you want to build, and Agent will take it from idea to working product:

  • A log formatter that combines numerical data and string descriptions into a structured output for easier debugging.
  • A simple inventory tracker that takes an item name and a quantity, then prints a formatted string like "You have 5 apples in stock."
  • A custom data exporter that formats user IDs and scores into a single string for easy migration to another system.

Simply describe your app, and Replit will write the code, test it, and fix issues automatically, all within your browser.

Common errors and challenges

Even with simple tasks like printing, you can run into a few common roadblocks that are easy to fix once you know what to look for.

Fixing TypeError when concatenating strings and numbers

Python strictly enforces data types, so you can't directly combine a string and an integer using the + operator. Attempting to do so will raise a TypeError because the operation isn't defined between these two types.

The solution is to explicitly convert the number to a string before concatenation. By wrapping the integer with the str() function, you tell Python to treat the number as text, allowing the + operator to join the pieces correctly.

Debugging nested quotes in f-strings

A common slip-up with f-strings is using the same type of quotation marks inside the string as you used to define it. For instance, f"The value is "{value}"" will cause a SyntaxError because Python thinks the string ends prematurely.

To fix this, simply alternate your quotation marks. If you start the f-string with double quotes, use single quotes for any strings inside it, like f"The value is '{value}'". The reverse also works perfectly.

Resolving missing format arguments in .format()

When using the .format() method, you might encounter an IndexError. This happens if the number of placeholders {} in your string exceeds the number of arguments you provide to the method. Python can't find a value for the extra placeholder and stops.

The fix is straightforward—double-check that every placeholder has a corresponding value in your .format() call. For example, if you have "{}, {}", you need to pass two arguments, like .format(arg1, arg2).

Fixing TypeError when concatenating strings and numbers

Python's + operator behaves differently for numbers (addition) and strings (concatenation). Because of this, mixing them without conversion causes a TypeError. The code below demonstrates what happens when you try to concatenate a string with an integer directly.

quantity = 5
item = "apples"
print("I have " + quantity + " " + item) # TypeError

The + operator can't perform addition between the string "I have " and the integer quantity. This type mismatch is what triggers the TypeError. The following example shows the correct way to handle it.

quantity = 5
item = "apples"
print("I have " + str(quantity) + " " + item) # Convert int to str

The solution is to explicitly convert the integer to a string by using str(quantity). This tells Python to treat the number as text, allowing the + operator to join the string pieces together correctly. It's a simple but crucial step to avoid a TypeError and ensure your code runs smoothly anytime you build a string by concatenating it with a number.

Debugging nested quotes in f-strings

Using the same quotation marks to define an f-string and for strings inside it will cause a SyntaxError. This happens because Python interprets the inner quote as the end of the string, breaking the code. The example below illustrates this exact problem.

name = "Alice"
print(f"She said "My name is {name}"") # SyntaxError

The inner double quotes cause Python to read f"She said " as the complete string, which leaves the rest of the line as invalid syntax. The following example shows how to resolve this conflict by alternating your quotation marks.

name = "Alice"
print(f'She said "My name is {name}"') # Use different outer quotes

The solution is to simply alternate your quotation marks. By starting the f-string with single quotes, as in f'She said "My name is {name}"', you can safely use double quotes inside it without confusing the Python interpreter. This swap prevents the SyntaxError. It's a good habit to check your quote usage whenever you're embedding strings that already contain quotes, especially when building complex text outputs.

Resolving missing format arguments in .format()

When using the .format() method, you'll get an IndexError if your string has more placeholders than the arguments you provide. Python raises this error because it can't find a value for every slot. The code below demonstrates this common mismatch.

name = "Bob"
print("Hello, {0}. Your ID is {1}.".format(name)) # IndexError

The code fails because the string expects two values for placeholders {0} and {1}, but you've only supplied one argument, name, to the .format() method. The following example shows how to resolve this.

name = "Bob"
id_number = "12345"
print("Hello, {0}. Your ID is {1}.".format(name, id_number)) # Add missing argument

The solution is to ensure every placeholder has a corresponding argument. The corrected code works because .format(name, id_number) now provides two values for the two placeholders, {0} and {1}, resolving the IndexError.

  • You'll often encounter this error when modifying a string template but forgetting to update the arguments passed to .format(). It’s a good habit to double-check that your placeholders and arguments are in sync.

Real-world applications

With the fundamentals and error-fixing covered, you can apply these printing skills to create useful outputs like formatted receipts and simple data charts.

Creating a formatted receipt with print()

Using the print() function with f-string format specifiers lets you control alignment and decimal precision, which is perfect for creating clean, column-based outputs like a customer receipt.

item1, price1 = "Coffee", 3.50
item2, price2 = "Sandwich", 5.75
total = price1 + price2

print(f"{'Item':<10}{'Price':>10}")
print(f"{'-'*20}")
print(f"{item1:<10}${price1:>9.2f}")
print(f"{item2:<10}${price2:>9.2f}")
print(f"{'-'*20}")
print(f"{'Total':<10}${total:>9.2f}")

This example showcases advanced f-string formatting to create a structured text layout. It combines several techniques for precise control over the final output.

  • Expressions like :<10 pad the string with spaces to a width of 10 characters and left-align the text.
  • The :>9.2f specifier formats a number as a float with two decimal places, right-aligning it within a 9-character space.
  • You can also evaluate simple expressions, such as '-'*20, directly inside the f-string to generate content dynamically.

Visualizing data with ASCII charts using print()

The print() function can also be used with string multiplication to create simple ASCII bar charts, letting you visualize data directly in your terminal.

data = {"Python": 35, "JavaScript": 30, "Java": 25, "C++": 10}

print("Programming Language Popularity:")
for language, value in data.items():
bar = "█" * int(value / 2) # Scale down for display
print(f"{language:.<15} {bar} {value}%")

This code iterates through a dictionary of programming languages and their popularity scores to create a simple bar chart. It's a great example of using basic tools for data visualization.

  • The for loop uses .items() to access both the language name and its score in each pass.
  • A visual bar is built by multiplying the "█" character. The score is divided by two so the chart doesn't get too wide.
  • The final print() uses an f-string to align everything neatly. The {language:.<15} specifier pads the text with dots, creating a clean, column-like layout.

Get started with Replit

Put your new skills to work with Replit Agent. Just describe your goal, like "build a tip calculator that prints a formatted receipt" or "create a tool that converts temperatures and displays the result."

Replit Agent writes the code, tests for bugs, and handles deployment. You just provide the vision. Start building with Replit.

Get started free

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.

Get started free

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.