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)
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
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.
mystr = "helloworld" print(len(mystr))
print("hello \nworld") print("hello \n world")
hello world hello world
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 = 'h' , this will give an error. Instead you will have to separately grab "at" from "cat" and add "h" to it.