Remove a character from a string using Python

This post introduces how to remove / replace a character from a string using Python.

In Python, strings are immutable, so we need to create a new string. If you want to remove the ‘;’ wherever it appears. See below for an example.

Remove character”;”

>>> original_str = "good; ok"
>>> new_str = original_str.replace(";","")
>>> print(new_str)
good ok

See the examples below for different ways to check whether a string contains a specific character.

>>> s = "good; ok"
>>> ";" in s
>>> ";" not in s
>>> s.find(";") == -1
>>> s. find(";") != -1
>>> chars = set(";o")
>>> if any((c in chars) for c in s):
>>> print("Found")
>>> import re
>>> pattern = re.compile(r";o")
>>> if pattern.findall(s):
>>> print("Found")



How to delete a character from a string using python?

Remove all special characters, punctuation and spaces from string

How to check a string for specific characters? (pdf)

Leave a Reply

Your email address will not be published.