Coders Packet

How to remove the sub string from the given string by using the Python

By Harshith Appari

Hello everyone in this tutorial we will learn about how to remove the sub string with the help of the length which is given by user by using Python

Hello Everyone, In this tutorial, how to delete the substring from the given string using Python.

Like we will usually see the string, and we will delete the substring by using the length

Where the length is accepted as the input from the user

example: hi, hello the code speedy is more beneficial for programmers

input: 4

That means it will delete all the substrings with the length of 4 from the main string

output: hi, the code speedy is beneficial for programmers

So let us see the code in Python

s=input()
k=int(input())
s2=s.split()
l=[]
s1=""
for i in s2:
  if len(i)!=k:
    l.append(i)
for i in l:
  if len(s1)==0:
    s1=s1+i
  else:
    s1=s1+" "+i
print(s1)

S is the main string that the user accepts

k is the length of the substring to remove from the main string

The split function is used to split the words in the main string and make them a list

l is the empty list and is used to store the words that are not of the length taken from the input

s1 is the empty string that is used to make a sentence of removing the substring

By using the for loop, we can check each word length matches or not matches

If it doesn't match, we will append the word to the empty list l

By using another for loop to construct the string that doesn't have the substring of the given length

Here if else is used to check the length of the empty string s1 if s1==0, then directly adding the substring to the empty string

Else we have to add the substring to the empty string and provide spaces between the words in the substring

At last printing, the string that doesn't contain the substring of the given length

hello the codespeedy is more useful for programmers as it include more programming languages 
enter the length of the sub string : 6
hello the codespeedy is more for programmers as it include more programming languages

 

Download Complete Code

Comments

No comments yet

Download Packet

Reviews Report

Submitted by Harshith Appari (Harshith)

Download packets of source code on Coders Packet