String Slicing & Operations on Strings

·

1 min read

String Slicing & Operations on Strings

In Python, we can perform various operations on strings like finding the length of a string, slicing a string, and looping through a string.

To find the length of a string, we can use the built-in len() function. For example:

fruit = "Mango"
len1 = len(fruit)
print(len1)

The output will be 5 as there are 5 characters in the string "Mango".

To slice a string, we can specify the start and end index of the substring we want to extract. For example:

pie = "ApplePie"
print(pie[:5]) #Slicing from Start
print(pie[5:]) #Slicing till End
print(pie[2:6]) #Slicing in between
print(pie[-8:]) #Slicing using negative index
        # In this case, the [-8:] notation specifies a slice that                                                                 starts from the eighth last element and goes until the end of the list.

The output will be:

Apple
Pie
pleP
ApplePie

To loop through a string, we can use a for loop. Since strings are iterable, we can loop through each character in the string. For example:

alphabets = "ABCDE"
for i in alphabets:
    print(i)

The output will be:

A
B
C
D
E

We can use these operations to manipulate and work with strings in Python.