Python string special operators

Concatenation operator ‘+’

‘+’ operator is used for concatenation. Concatenation means combining, when + operator is used with string the string on right side of the operator is added to the string on the left side of the operator.

Look at the example given below, var1 has the value of ‘Welcome’, var2 has the value of ‘John’. var3 = var1 + var2 = ‘Welcome’ + ‘John’ = ‘Welcome John’

var1 = 'Welcome '
var2 = 'John'
var3 = var1 + var2
print ("'welcome ' + 'John' = " + var3)

Download the code Run the code

Repetition of string using * operator

‘*’ is used to repeat multiple copies of same string. If you look at the code given below, var1 has the value = ‘Welcome’ and var2 = var1*6 = var1 + var1 + var1 + var1 + var1 + var1.

var1 = 'Welcome '
var2 = var1*6
print ("'welcome ' * 6 = " + var2)

Download the code Run the code

Retrieving character from a given index of string

If you want to know which is the character at a particular location in string then that can be done easily. The first character in the string is at position 0, the second character is at position 1, the third character is at index 2 and so on.

In the following piece of code, var1 has the value of ‘Welcome’. Here we try to find out which character is present at second position which means index 1.

var1 = 'Welcome '
print ("The second character in string 'welcome ' is " + var1[1])

Download the code Run the code

Range of slice

Range of slice is used when you want to retrieve a certain section of the string. In the code shown below we try to retrieve four characters from the string var1 starting from second position i.e. index 1.

var1 = 'Welcome '
print ("The second to fourth characters in string 'welcome ' are " + var1[1:5])

Download the code Run the code

String operator ‘in’

String operator ‘in’ returns a Boolean value of either true or false. If the pattern of characters that you are searching for exists in the string then it will return the value of ‘true’ or else it will return ‘false’

var1 = 'Welcome'
if 'e' in var1: print ("'e' exists in the word 'welcome'")
else: print ("'e' does not exist in the word 'welcome'")

Download the code Run the code

String operator ‘not in’

String operator ‘not in’ returns a Boolean value of either true or false. If the pattern of characters that you are searching for does not exist in the string then it will return the value of ‘true’ or else it will return ‘false’.

var1 = 'Welcome'
if 'e' not in var1: print ("'e' does not exist in the word 'welcome'")
else: print ("'e' exists in the word 'welcome'")

Download the code Run the code

<<< Python escape charactersBuilt-in string operations in Python >>>
Copyright 2005-2016 KnowledgeHills. Privacy Policy. Contact .