Back to Python
2026-01-156 min read

Example 2: Addition of string and integer Using Explicit Conversion (Python Programming)

Learn Example 2: Addition of string and integer Using Explicit Conversion (Python Programming) step by step with clear examples and exercises.

Why This Matters

In Python programming, understanding how to add a string and an integer using explicit conversion is crucial for solving various real-world problems and troubleshooting bugs in your code. This lesson will provide you with a solid foundation for working with different data types and performing arithmetic operations in Python. Let's dive deeper into the topic!

Prerequisites

Before we proceed, it is essential to have a good understanding of the following concepts:

  1. Basic Python syntax (variables, operators)
  2. Data types in Python (strings, integers)
  3. Type casting or type conversion in Python
  4. Conditional statements (if-else)
  5. Exception handling (try-except)

If you're not familiar with these topics, don't worry! We will briefly touch upon them as we progress through this lesson.

Core Concept

In Python, a string and an integer are two different data types that cannot be directly added together. However, we can add them by converting the string to an integer using explicit conversion. This is done using the built-in int() function in Python.

str_num = "5"
int_num = int(str_num) + 3
print("Integer sum:", int_num)

In this example, we first create a string variable str_num with the value of "5". Then, we convert the string to an integer using the int() function and store the result in the variable int_num. Finally, we add 3 to int_num and print the result as an integer.

String Concatenation vs Addition

Note that that the + operator performs string concatenation when used with strings. To avoid confusion, it's a good practice to use separate variables for storing strings and integers, as shown in our example above.

str_num = "5"
int_num = int(str_num)
sum_as_string = str(int_num) + "+" + str(3) # Concatenate the numbers as strings for clarity
print("String sum:", sum_as_string)

In this example, we first convert str_num to an integer and store it in int_num. Then, we concatenate the integers as strings (using +) along with the "+" operator to create a string representation of the sum. This can help clarify our code when dealing with both strings and integers.

Worked Example

Let's work through a more complex example together:

str1 = "20"
str2 = "30"
sum_as_string = str1 + str2
sum_as_number = int(sum_as_string)
print("Sum as string:", sum_as_string)
print("Sum as number:", sum_as_number)

In this example, we have two strings str1 and str2, each containing a number. We first concatenate them to get the sum as a string using the + operator. Then, we convert the concatenated string back to an integer using the int() function. Finally, we print both the sum as a string and the sum as a number.

Handling Empty Strings

It's worth mentioning that if either str1 or str2 is an empty string, concatenating them will result in another empty string. In this case, converting the empty string to an integer using int() will throw a ValueError. To handle this situation gracefully, we can add a conditional statement (if-else) to check if the strings are empty before performing the conversion:

str1 = "20"
str2 = ""

if str2 != "": # Check if str2 is not an empty string
sum_as_string = str1 + str2
sum_as_number = int(sum_as_string)
else:
print("Error: One of the strings is empty.")

In this example, we check if str2 is not an empty string before concatenating and converting it to an integer. If str2 is empty, we print an error message instead.

Common Mistakes

  1. Forgetting to convert the string to an integer: If you forget to convert the string to an integer after concatenating them, Python will throw a TypeError since it cannot perform arithmetic operations on strings and integers directly.
str1 = "20"
str2 = "30"
sum_as_string = str1 + str2
print(sum_as_string) # Output: 2030 (TypeError if you try to perform arithmetic operations on this)
  1. Incorrectly converting the string to an integer: If you convert a non-numeric string to an integer, Python will throw a ValueError because it cannot interpret the string as a valid number.
str1 = "apple"
int_num = int(str1)
print(int_num) # Output: ValueError: invalid literal for int() with base 10: 'apple'
  1. Not handling the case when one of the strings is empty: If either str1 or str2 is an empty string, concatenating them will result in another empty string. In this case, converting the empty string to an integer using int() will throw a ValueError. To handle this situation gracefully, we can add a conditional statement (if-else) to check if the strings are empty before performing the conversion, as shown in our previous example.
  1. Not handling non-numeric strings: When working with user input or external data sources, it's essential to validate and clean the data before converting them to integers. This can help prevent errors caused by non-numeric strings.
str1 = input("Enter the first number: ")
if str1.isdigit(): # Check if the string contains only digits
int_num1 = int(str1)
else:
print("Error: The entered value is not a valid number.")

In this example, we use the input() function to get user input. Then, we check if the string contains only digits using the isdigit() method before converting it to an integer. This helps ensure that our code handles non-numeric strings gracefully.

Practice Questions

  1. Write a Python code to add the two strings "10" and "20" and print the result as both a string and an integer.
  2. Given two strings str1 = "70" and str2 = "50", write a Python code to find the sum of their digits and print the result.
  3. Write a Python function that takes two strings representing numbers and returns their sum as an integer. The function should handle empty strings, non-numeric strings, and negative numbers gracefully by returning an error message in such cases.
  4. Write a Python program that takes a list of strings representing integers and calculates the sum of those integers. Your program should handle empty strings, non-numeric strings, and negative numbers gracefully by skipping invalid inputs and printing the final result.

FAQ

  1. Why can't I directly add a string and an integer in Python?
  • In Python, a string and an integer are two different data types that cannot be directly added together. However, we can add them using explicit conversion.
  1. What happens if I try to perform arithmetic operations on a concatenated string of numbers in Python?
  • If you try to perform arithmetic operations on a concatenated string of numbers, Python will throw a TypeError because it cannot perform arithmetic operations on strings and integers directly.
  1. What should I do if my code throws a ValueError when converting a non-numeric string to an integer in Python?
  • If your code throws a ValueError when converting a non-numeric string to an integer, it means that the string cannot be interpreted as a valid number. You can handle this by checking if the string is numeric before converting it to an integer or by catching the ValueError and returning an error message.
  1. How can I validate user input in Python to ensure it's a valid number?
  • To validate user input in Python, you can use conditional statements (if-else) or regular expressions (regex) to check if the entered value is a valid number. You can also provide clear instructions to the user about the expected format for their input.
Example 2: Addition of string and integer Using Explicit Conversion (Python Programming) | Python | XQA Learn