Skip to content
Programming Problems · Q3

Q.Write a function deleteChar() which takes two parameters one is a string and 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.

West Bengal WbchseTextbookSubjective· 3mImportance★★★★★est
85% · 11/13 Questions
🔒 Locked · start free trial →

You're viewing a preview — the full solution, concept, methods & PYQ mapping are locked.

Start your 14-day free trial to unlock the full solution →

Since strings are immutable, "deleting" means building a NEW string that copies every character except the unwanted one — one loop with a simple inequality test.

Idea. A Python string cannot be edited in place, so the function creates an empty result string and walks the original once: characters equal to the target are skipped, all others are appended. This removes all occurrences, exactly as asked, and the original string remains unchanged — the new string is returned.

def deleteChar(st, ch):
    """Return a new string with all occurrences of ch removed from st."""
    newStr = ""
    for c in st:
        if c != ch:          # keep every character that is NOT ch
            newStr += c
    return newStr

# main program
s = input("Enter a string: ")
c = input("Enter the character to delete: ")
result = deleteChar(s, c)
print("Original string:", s)
print("String after deletion:", result)

Trace for deleteChar("banana", "a") — watch newStr grow:

Stepcc != 'a'?newStr after step
1byes — appendb
2ano — skipb
3nyes — appendbn
4ano — skipbn
5nyes — appendbnn
6ano — skipbnn

Unlock everything free for 14 days

  • Full step-by-step solutions
  • Concept-first explanations
  • Methods, shortcuts & mistakes
  • PYQ mapping + timed mock tests

Full access for 14 days. No credit card required.