Multiple ways that we can remove letters from a String using Python.

python @ Freshers.in

In this article you can see multiple ways that we can remove letters from a String using Python.

my_string = "mytesting_word"
to_replace = 'my'
m1 = my_string.replace(to_replace,'')
print(f"Replaced word is : {m1}")
Replaced word is : testing_word

The replace() method replaces a specified phrase with another specified phrase.

m2 = my_string[2:]
print(f"Replaced word is : {m2}")

Replaced word is : testing_word

The : symbol operator slices a part from a sequence object such as list, tuple or string. It takes two arguments. First is the index of start of slice and second is index of end of slice. Both operands are optional. If first operand is omitted, it is 0 by default.

m3 = my_string.partition('my')[2]
print(f"Replaced word is : {m3}")

Replaced word is : testing_word

The partition() method searches for a specified string, and splits the string into a tuple containing three elements.
The first element contains the part before the specified string.
The second element contains the specified string.
The third element contains the part after the string.

m4 = slice(2, 14)
print(f"Replaced word is : {my_string[m4]}")

Replaced word is : testing_word

A slice object is used to specify how to slice a sequence. You can specify where to start the slicing, and where to end. You can also specify the step, which allows you to e.g. slice only every other item.

import re
m5 = re.sub(r'my','',my_string)
print(f"Replaced word is : {m5}")

Replaced word is : testing_word

Regular expression : Return the string obtained by replacing the leftmost non-overlapping occurrences of pattern in string

m6 = my_string.strip('my')
print(f"Replaced word is : {m6}")

Replaced word is : testing_word

Returns a copy of the string with both leading and trailing characters removed

Author: user

Leave a Reply