Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Can we do math operation on Python Strings?
Python strings support certain mathematical operations, but they behave differently than numeric operations. You can use + for concatenation, * for repetition, and eval() for evaluating mathematical expressions stored as strings.
String Concatenation with +
The + operator concatenates strings together to form a single string ?
string1 = "Lorem " string2 = "Ipsum" result = string1 + string2 print(result)
Lorem Ipsum
String Repetition with *
The * operator repeats a string a specified number of times ?
string1 = "Hello" result = string1 * 3 print(result)
HelloHelloHello
Arithmetic Operations Don't Work Directly
When you try to add numeric strings, Python concatenates them instead of performing arithmetic ?
string1 = "5"
string2 = "2"
result = string1 + string2
print(result)
print("To perform math, convert to int:", int(string1) + int(string2))
52 To perform math, convert to int: 7
Using eval() for Mathematical Expressions
The eval() function evaluates mathematical expressions written as strings ?
Basic Operations
# Addition
addition = eval("3 + 5")
print("Addition:", addition)
# Multiplication
multiplication = eval("4 * 6")
print("Multiplication:", multiplication)
Addition: 8 Multiplication: 24
Complex Expressions
expression = "2 * (4 + 6) / 3 - 5"
result = eval(expression)
print("Complex expression result:", result)
Complex expression result: 1.6666666666666667
Error Handling with eval()
expression = "3 / 0"
try:
result = eval(expression)
print("Result:", result)
except ZeroDivisionError:
print("Division by zero is not allowed!")
except Exception as e:
print("Error:", e)
Division by zero is not allowed!
Comparison of String Operations
| Operator | Operation | Example | Result |
|---|---|---|---|
+ |
Concatenation | "Hello" + " World" |
"Hello World" |
* |
Repetition | "Hi" * 3 |
"HiHiHi" |
eval() |
Expression evaluation | eval("2 + 3") |
5 |
Security Warning with eval()
Important: The eval() function can execute any Python code, making it a security risk. Only use it with trusted input or consider safer alternatives like ast.literal_eval() for simple expressions.
Conclusion
While Python strings support + (concatenation) and * (repetition), true mathematical operations require converting strings to numbers or using eval() with caution. Always validate input when using eval() to prevent security vulnerabilities.
