w3resource

Python: Remove unwanted characters from a given string

Python String: Exercise-89 with Solution

Write a Python program to remove unwanted characters from a given string.

Sample Solution:

Python Code:

# Define a function to remove unwanted characters from a string
def remove_chars(str1, unwanted_chars):
    # Iterate through each unwanted character
    for i in unwanted_chars:
        # Use the replace() method to remove occurrences of the unwanted character from the string
        str1 = str1.replace(i, '')
    
    # Return the modified string without unwanted characters
    return str1

# Initialize two strings
str1 = "Pyth*^on Exercis^es"
str2 = "A%^!B#*CD"

# Specify a list of unwanted characters
unwanted_chars = ["#", "*", "!", "^", "%"]

# Print the original string and a message indicating the removal of unwanted characters
print("Original String : " + str1)
print("After removing unwanted characters:")
# Call the function to remove unwanted characters and print the result
print(remove_chars(str1, unwanted_chars))

# Print a newline for better formatting
print("\nOriginal String : " + str2)
print("After removing unwanted characters:")
# Call the function to remove unwanted characters and print the result
print(remove_chars(str2, unwanted_chars)) 

Sample Output:

Original String : Pyth*^on Exercis^es
After removing unwanted characters:
Python Exercises

Original String : A%^!B#*CD
After removing unwanted characters:
ABCD

Flowchart:

Flowchart: Check whether a given string has a capital letter, a lower case letter, a number and specified length.

Python Code Editor:

Previous: Write a Python program to check whether a given string contains a capital letter, a lower case letter, a number and a minimum length.
Next: Write a Python program to remove duplicate words from a given string.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.