String Properties

Mathematical operations on strings

Python is known for its dealing with strings. It provides flexibility , readability and at the same time makes the whole process simpler. let us perform some operations.

Addition : The ability to add multiple strings to form a new string is called Concatenation. Let us explore this with few examples.

In this example we have assigned “hello” to x and “world” to y and our aim is to print “helloworld” and for that we need to add the two strings(x+y).

x = "hello"  y = "world"  print(x+y)

output:
helloworld

Multiplication : Multiplication allows us to perform multiple concatenation at once. Say you have a string “hello” and you want to get “hellohellohello” as output than instead of adding them three times( “hello” + “hello” + “hello”) , we can simply multiply “hello” with 3 ( 3 * “hello”) to get the same output. Let us write and run the same code in the editor

output:
hellohellohello  hellohellohello

Can you predict the output of the following code??

print( '3' + '5')

Here the data types of 3 and 5 aren’t integer , rather they are strings. so instead of adding the two number as integers , python will perform string concatenation and produce the output as 35.

The length of the string can easily be calculated using the len() function. Simply place the string within the parenthesis to get the result. Often you’ll be using lengths of the string as a condition in loops( discussed in later sections ).
mystr = "helloworld"  print(len(mystr))

output :
10

If the string contains a single quote ( don’t , can’t … ) than make sure to enclose it under double quotes and not single quote ( you will get an error if you use single quote).
‘don’t’
‘can’t’
“don’t”
“can’t”

While writing a string , use ‘n’ if you want to switch to the next line.
print("hello nworld")  print("hello n world")

output :
hello  world  hello    world

Comments can be added using # in Python . The comments are never executed and shall have no effect on the optimization of the code. They are helpful in explaining what a specific section of the code does.

Strings in Python are immutable.

Operations like indexing and slicing can be performed on strings however it is not possible to reassign a different value to a specific index of the string. Let us understand this with an example. Say you have a string “cat” and you wanna convert it to ” hat”. You cannot do something like cat[0] = ‘h’ , this will give an error. Instead you will have to separately grab “at” from “cat” and add “h” to it.