Operations on Strings in Python

Let's explore operations on String with easy examples!

Like numbers datatype, we can also do some operations on String datatype. These operations include addition, multiplication, and type conversion.

Let’s see some examples to understand more about these operations.

Arithmetic Operation on String

We all have done arithmetic operations on numeric data. The question is, do these arithmetic operations work on String?

The answer is Yes!

Let’s try to find out how these work.

First, let’s once see how it works with numbers and then with Strings.

num = 2
print(num + num)

"""
output:

4

"""

We can add strings to each other with the “+” operator. This is called the concatenation of string.

Let’s try to add some strings!

print("Hello" + "From" + "Co-Learning Lounge") # Adding three strings (Concating string)

"""
output:

HelloFromCo-Learning Lounge

"""

We can also add space to the above example. Spaces are important and should be carefully used, so the result is readable.

print("Hello" + " " + "From" + " " + "Co-Learning Lounge") #Adding three strings (Concating string)
print("Hello " + "From " + "Co-Learning Lounge") #Adding space at the end of each word.

"""
output:

Hello From Co-Learning Lounge
Hello From Co-Learning Lounge

"""
## Strings and Arithmetic Operators

Stringnum = "2"
print(Stringnum + Stringnum)

"""
output:

22

"""

 

We can also multiply integers by strings and it results in a number of the same string!

print("Hello From Co-Learning Lounge, " * 3 )

"""
output:

Hello From CLL, Hello From CLL, Hello From CLL,

"""
char = "*"
print(char * 3)

"""
output:

***

"""

Can we also multiply a string by a float instead of an integer??

Think about it, does it make sense?

It doesn’t, right? So Python doesn’t do something which doesn’t make sense!

Let’s see!

print("*" * 3.0)

"""
output:

---------------------------------------------------------------------------

TypeError                                 Traceback (most recent call last)

<ipython-input-5-b7c4106eb299> in <module>
----> 1 print("*" * 3.0)


TypeError: can't multiply sequence by non-int of type 'float'

"""

 

print("*" * 3.1)

"""
output:

---------------------------------------------------------------------------

TypeError                                 Traceback (most recent call last)

<ipython-input-34-edfbe3bdb87c> in <module>
----> 1 print("*" * 3.1)


TypeError: can't multiply sequence by non-int of type 'float'

"""

Multiplying a string datatype to a string datatype doesn’t make sense. Hence it doesn’t work!

Here it is:

print("12" * "3")

"""
output:

---------------------------------------------------------------------------

TypeError                                 Traceback (most recent call last)

<ipython-input-73-244ef441043f> in <module>()
----> 1 print("12" * "3")


TypeError: can't multiply sequence by non-int of type 'str'

"""

Similarly, the division also doesn’t work on Strings!

print("*"/3)

"""
output:

---------------------------------------------------------------------------

TypeError                                 Traceback (most recent call last)

<ipython-input-6-edaaf23b19f4> in <module>
----> 1 print("*"/3)


TypeError: unsupported operand type(s) for /: 'str' and 'int'

"""

Also, we can only concatenate one string to another. It is not possible to concatenate a string to any other datatype.

Let’s try to concatenate a string to a number!

print("3" + 3)

"""
output:

---------------------------------------------------------------------------

TypeError                                 Traceback (most recent call last)

<ipython-input-75-ebb67c5e5687> in <module>()
----> 1 print("3" + 3)


TypeError: can only concatenate str (not "int") to str

"""

But we can change another datatype to string to concatenate!

Let’s try to add by converting!

print("3" + str(3))  #We are converting number to String before concatinating
print("3" + "3")    #This is same as previous statement

"""
output:

33
33

"""

We can convert different datatypes to String. This is called typecasting or type conversion.

Let’s see examples of converting datatypes to strings to use these operations!

from traitlets.config.application import boolean_flag

boolean = True
integer = 3
flt = 34.5
string = "Hello"

print(type(boolean))
print(type(str(boolean)))

print(type(str(integer)))
print(str(integer))

print(type(str(flt)))
print(str(flt))

"""
output:

<class 'bool'>
<class 'str'>
<class 'str'>
3
<class 'str'>
34.5

"""
print(type(bool(string)))
print(bool(string))
print(bool(""))
print(bool(" "))

print(type(bool(integer)))
print(bool(integer))

print(type(bool(flt)))
print(bool(flt))

"""
output:

<class 'bool'>
True
False
True
<class 'bool'>
True
<class 'bool'>
True

"""
print(type(int(boolean)))
print(int(boolean))

print(type(int(flt)))
print(int(flt))

print(type(int(string)))
print(int(string))

"""
output:

<class 'int'>
0
<class 'int'>
34



---------------------------------------------------------------------------

ValueError                                Traceback (most recent call last)

<ipython-input-29-fff90515dd2a> in <module>
      5 print(int(flt))
      6 
----> 7 print(type(int(string)))
      8 print(int(string))


ValueError: invalid literal for int() with base 10: 'Hello'

"""
print(type(float(boolean)))
print(float(boolean))

print(type(float(integer)))
print(float(integer))

print(float(int(string)))
print(float(string))

"""
output:

<class 'float'>
1.0
<class 'float'>
3.0



---------------------------------------------------------------------------

ValueError                                Traceback (most recent call last)

<ipython-input-32-dd24dc7daacc> in <module>
      5 print(float(integer))
      6 
----> 7 print(float(int(string)))
      8 print(float(string))


ValueError: invalid literal for int() with base 10: 'Hello'

"""

We have tried basic arithmatic operations on strings and touched on typecasting to convert datatypes and use these operations.

About Post Author

Spread the love

Leave a Comment

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

Must Read

Scroll to Top