w3resource

Python: Strip a set of characters from a string


Strip specific characters from string.

Write a Python program to strip a set of characters from a string.

Python String Exercises: Strip a set of characters from a string

Sample Solution:

Python Code:

# Define a function 'strip_chars' that takes a string 'str' and a string 'chars' as input.
# The function returns a new string containing characters from 'str' that are not in 'chars'.
def strip_chars(str, chars):
    return "".join(c for c in str if c not in chars)

# Print an empty line for spacing.
print()

# Print the original string.
print("Original String: ")
print("The quick brown fox jumps over the lazy dog.")

# Print a message indicating the characters to be stripped from the string.
print("After stripping a, e, i, o, u")

# Call the 'strip_chars' function with the input string and the characters to strip,
# and then print the result.
print(strip_chars("The quick brown fox jumps over the lazy dog.", "aeiou"))

# Print an empty line for spacing.
print() 

Sample Output:

Original String:                                                                                              
The quick brown fox jumps over the lazy dog.                                                                  
After stripping a,e,i,o,u                                                                                     
Th qck brwn fx jmps vr th lzy dg.                             

Flowchart:

Flowchart: Strip a set of characters from a string

For more Practice: Solve these Related Problems:

  • Write a Python program to strip a set of specified characters from both the beginning and end of a string.
  • Write a Python program to implement a function that removes given characters from a string using str.strip().
  • Write a Python program to use regular expressions to remove all occurrences of a specific set of characters from the ends of a string.
  • Write a Python program to manually remove unwanted characters from a string by iterating over its characters.

Go to:


Previous: Write a Python program to reverse words in a string.
Next: Write apython program to count repeated characters in a string.

Python Code Editor:

Contribute your code and comments through Disqus.

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.