Concepts

Computer Science - Class 11
Chapter 8 Class 11 - Strings

## 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:

## Repetition

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

Example:

### 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:

### 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:

## 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

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

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

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.

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

Get live Maths 1-on-1 Classs - Class 6 to 12