Crus4

logo

What Arithmetic Operators Cannot Be Used With Strings in Python


Arithmetic Operators such as Subtraction (-), division (/) and exponentiation (**) cannot be used with strings in Python. Instead these operators are only used to perform mathematical operations on numerical values (integers and floats).

You can only use the Addition Operator (+) and Multiplication Operator with strings in Python. Addition Operator is only used to concatenate the two strings, not with string and an integer. For Example:

str1 = "hello"
str2 = "world"
result = (str1 + str2)
print(result)

Output

helloworld

But if you use the addition operator with a string and an integer. It will produce an error. Here is an example:

Example

a = "Hello"
b = 123
print (a+b) #outputs: Tyeerror

Multiplication Operator with Strings in Python

Multiplication operator (*) can also be used with strings in Python. It is used to repeat a string by multiplying a string and an integer. Here is an example:

Example

a = "Hello"
b = 2
print (a*b) #outputs: HelloHello

If you use multiplication operator with strings, or try to multiple a string with a non-integer value you will get an error. Here is an example:

Example

a = "Hello"
b = "Yes"
print (a*b) #outputs: error

If you use any other operator other than addition and multiplication in Python, you will get an error. For example the below code will produce an error.

str1 = "hello"
str2 = "world"
result = (str1 - str2)
print(result)

This Code will produce an error.


Share This Post!

What Arithmetic Operators Cannot Be Used With Strings in Python

Leave a Reply

Your email address will not be published. Required fields are marked *