The previous article explained the functions involved in manipulating string data in Python, such as extracting or splicing string objects. This article explains the methods of concatenating strings by using string operators. However, it is important to understand the differences in the terms ‘string sequence’ ‘string object’, and ‘string literals’ in Python.
String sequence and string literals are similar
String sequence refers to the entire sequence of characters. However, there is a very similar term, ‘string literal’, which refers to that sequence of characters, present between single or double quotes, which has been given as input. Essentially, string literals and string sequences are similar.
x = 'Hi, how are you?' print(x)
#OUTPUT Hi, how are you?
In this example, variable x has a string sequence and string literal, while x is the variable. However, when Python reads the variable x, it stores the information as a string object. When the variable x is printed, the Python Interpreter will not create a new string, but simply consider the reference of the existing string object.
Using the var.replace() method to
Another way to overwrite existing string objects is by using the var.replace() method.
x = ‘Hi, how have you been?’ print(x.replace(“how”, “where”))
#OUTPUT Hi, where have you been?
Using the string operator ‘+’ for concatenation
The ‘+’ operator in Python can also be used to join string objects, end-to-end, to create a new string object in Python. The act of linking objects in a series is known as concatenation.
a='Bat' b='man' print(a+b)
It is also possible to include escape sequences with concatenation. This is especially useful when the sequence has been assigned to a variable. So instead of rewriting the entire string sequence, simply edit the sequence using appropriate escape sequences.
x = 'Dont cry' print(x+'\beate')
#OUTPUT Dont create
Concatenating using var.join()
Concatenation can also be done by using the function, str.join(). This function combines two different string objects by passing one string through another.
Suppose, we have a string object, ‘Maryhadalittlelamb’ and we now want to add ‘_’ between each letter.
a = 'Maryhadalittlelamb' print('_'.join(a))
Using the string operator ‘*’ to multiply the object ‘n’ times
The ‘*’ can be used to multiply the string object ‘n’. Whereas n is the number of times the string has to be concatenated.
x = 'Strong ' print(x*10)
#OUTPUT Strong Strong Strong Strong Strong Strong Strong Strong Strong Strong