Can we do math operation on Python Strings?


You can perform some math operations on Python strings technically, but it may not work the way you expect it to. Here are a few examples:

Concatenating Strings with +

Example

In this example, we concatenate two strings by using the + operator. This works because the + operator is overloaded in Python to work with strings as well as numbers. When we use the + operator with strings, it concatenates them together to form a single string.

string1 = "Lorem "
string2 = "Ipsum"
result = string1 + string2
print(result)

Output

Lorem Ipsum

Multiplying Strings with *

Example

In this example, we multiply a string by an integer using the * operator. This works because, like the + operator, the * operator is overloaded in Python to work with strings as well as numbers. When we use the * operator with a string and an integer, it repeats the string a specified number of times.

string1 = "Hello"
result = string1 * 3
print(result)

Output

HelloHelloHello

Performing Arithmetic Operations with Strings (Doesn't Work)

Example

In this example, we try to add two strings together that represent numbers. However, instead of performing addition, Python concatenates the two strings together, resulting in the string "52". This is because Python treats strings as text, not numbers, so it doesn't perform arithmetic operations on them.

string1 = "5"
string2 = "2"
result = string1 + string2
print(result)

Output

52

Using eval() function

The eval() function can be used to evaluate mathematical expressions written as strings in Python. Here are four code examples with explanations that demonstrate how to use eval() function to perform math operations on string expressions:

Addition of Two Numbers

Example

In this example, we define a string expression that represents the addition of two numbers. We then use the eval() function to evaluate the expression and store the result in the result variable. Finally, we print the result to the console.

expression = "3 + 5"
result = eval(expression)
print(result)

Output

8

Multiplication of Two Numbers

Example

In this example, we define a string expression that represents the multiplication of two numbers. We then use the eval() function to evaluate the expression and store the result in the result variable. Finally, we print the result to the console.

expression = "4 * 6"
result = eval(expression)
print(result)

Output

24

Evaluation of a Complex Expression

Example

In this example, we define a string expression that represents a more complex mathematical expression involving multiple operations. We then use the eval() function to evaluate the expression and store the result in the result variable. Finally, we print the result to the console.

expression = "2 * (4 + 6) / 3 - 5"
result = eval(expression)
print(result)

Output

1.66666667

Error Handling for Invalid Expression

Example

In this example, we define a string expression that involves division by zero, which is not allowed in mathematics. We use a try-except block to catch the ZeroDivisionError exception that is raised when the eval() function tries to evaluate the expression. Instead of printing the error message, we print a custom error message to the console to inform the user that division by zero is not allowed.

expression = "3 / 0"
try:
    result = eval(expression)
except ZeroDivisionError:
    print("Division by zero is not allowed!")
else:
    print(result)

Output

Division by zero is not allowed!

In summary, while you can perform some math operations on Python strings, it's important to understand the limitations and how they work to avoid unexpected results. It's generally best to use math operations on numerical values, and string operations on strings.

It is found that eval() function can be used to perform mathematical operations on string expressions. However, it's important to be careful when using it, since it can also evaluate potentially dangerous code. Always make sure to only evaluate trusted code and validate any user input to prevent potential security vulnerabilities.

Updated on: 10-Aug-2023

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements