String Operations

As we know that string is a sequence of characters. Python allows certain operations on string data type, such as concatenation, repetition, membership and slicing.

Concatenation

Python allows us to join two strings using the concatenation operator plus which is denoted by symbol + .

Example:

Untitled 1.jpg

Repetition

Python allows us to repeat the given string using repetition operator which is denoted by symbol * .

Example:

Untitled 4.jpg

Membership

Python has two membership operators 'in' and 'not in'

In operator

The 'in' operator takes two strings and returns True if the first string appears as a substring in the second string, otherwise it returns False.

Example:

Untitled 5.jpg

Not in operator

The 'not in' operator also takes two strings and returns True if the first string does not appear as a substring in the second string, otherwise returns False. 

Example:

Untitled 6.jpg

Slicing

In Python, to access some part of a string or substring , we use a method called slicing. This can be done by specifying an index range. 

  • Given a string str1, the slice operation str1[n:m] returns the part of the string str1 starting from index n (inclusive) and ending at m (exclusive). 
  • In other words, we can say that str1[n:m] returns all the characters starting from str1[n] till str1[m-1]. 
  • The numbers of characters in the substring will always be equal to the difference of two indices m and n, i.e., (m-n). 

Examples:

  1. Gives substring from index 3 to 8

Untitled 7.jpg

2. If the first index is not mentioned, the slice starts from index 0

Untitled 8.jpg

3. If the second index is not mentioned, the slicing is done till the length of the string.

Untitled 9.jpg

4. The slice operation can also take a third index that specifies the ‘step size’ . For example, str1[n:m:k], means every k th character has to be extracted from the string str1 starting from n and ending at m-1. By default, the step size is one.

Untitled 10.jpg

5. If we ignore both the indexes and give step size as -1, the string is printed in reverse.

Untitled 11.jpg

 

Go Ad-free
Davneet Singh's photo - Co-founder, Teachoo

Made by

Davneet Singh

Davneet Singh has done his B.Tech from Indian Institute of Technology, Kanpur. He has been teaching from the past 14 years. He provides courses for Maths, Science and Computer Science at Teachoo