w3resource

Python: Remove all characters except a specified character in a given string

Python String: Exercise-72 with Solution

Write a Python code to remove all characters except a specified character in a given string.

Sample Solution:

Python Code:

def remove_characters(str1,c):
    return ''.join([el for el in str1 if el == c])
text = "Python Exercises"
print("Original string")
print(text)
except_char = "P"
print("Remove all characters except",except_char,"in the said string:")
print(remove_characters(text,except_char))
text = "google"
print("\nOriginal string")
print(text)
except_char = "g"
print("Remove all characters except",except_char,"in the said string:")
print(remove_characters(text,except_char))
text = "exercises"
print("\nOriginal string")
print(text)
except_char = "e"
print("Remove all characters except",except_char,"in the said string:")
print(remove_characters(text,except_char))

Sample Output:

Original string
Python Exercises
Remove all characters except P in the said string:
P

Original string
google
Remove all characters except g in the said string:
gg

Original string
exercises
Remove all characters except e in the said string:
eee

Flowchart:

Flowchart: Remove all characters except a specified character in a given string

Visualize Python code execution:

The following tool visualize what the computer is doing step-by-step as it executes the said program:


Python Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a Python program to move all spaces to the front of a given string in single traversal.
Next: Write a Python program to count Uppercase, Lowercase, special character and numeric values in a given string.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Python: Tips of the Day

What is the difference between Python's list methods append and extend?

append: Appends object at the end.

x = [1, 2, 3]
x.append([4, 5])
print (x)

Output:

[1, 2, 3, [4, 5]]

extend: Extends list by appending elements from the iterable.

x = [1, 2, 3]
x.extend([4, 5])
print (x)

Output:

[1, 2, 3, 4, 5]

Ref: https://bit.ly/2AZ6ZFq