हिंदी

Write a function deleteChar() which takes two parameters one is a string and the other is a character. The function should create a new string after deleting all occurrences of the character

Advertisements
Advertisements

प्रश्न

Write a function deleteChar() which takes two parameters one is a string and the other is a character. The function should create a new string after deleting all occurrences of the character from the string and return the new string.

संक्षेप में उत्तर
Advertisements

उत्तर

Program 1:
#deleteChar function to delete all occurrences of char from string using replace() function
def deleteChar(string,char):
    #each char is replaced by empty character
    newString = string.replace(char,'')
    return newString

userInput = input("Enter any string: ")
delete = input("Input the character to delete from the string: ")

newStr = deleteChar(userInput,delete)

print("The new string after deleting all occurrences of",delete,"is: ",newStr)

OUTPUT:
Enter any string: Good Morning!
Input the character to delete from the string: o
The new string after deleting all occurrences of o is: Gd Mrning!


Program 2:
#deleteChar function to delete all occurrences of char from string without using replace() function
def deleteChar(string,char):
    newString = ''
    #Looping through each character of string
    for a in string:
        #if character matches, replace it by empty string
        if a == char:
            #continue
            newString += ''
        else:
            newString += a
    return newString

userInput = input("Enter any string: ")
delete = input("Input the character to delete from the string: ")

newStr = deleteChar(userInput,delete)

print("The new string after deleting all occurrences of",delete,"is: ",newStr)

OUTPUT:
Enter any string: Good Evening!
Input the character to delete from the string: o
The new string after deleting all occurrences of o is: Gd Evening!
shaalaa.com
String Handling in Python
  क्या इस प्रश्न या उत्तर में कोई त्रुटि है?
अध्याय 8: Strings - Exercise [पृष्ठ १८८]

APPEARS IN

एनसीईआरटी Computer Science [English] Class 11
अध्याय 8 Strings
Exercise | Q 3. | पृष्ठ १८८
Share
Notifications

Englishहिंदीमराठी


      Forgot password?
Use app×