Remove a character from a string in python

Remove a character from a string in python


A character in python is represented using a Unicode code point.  The unicode code point is written by using U+ followed by a number written in hexadecimal.

Strings are arguably the commonly used data type in python and when used to such an extent you come across a plethora of errors. We often pronounce char as character. Out of which the most common ones are the new tab escape sequence \n getting appended to the ending of a string or special char in the place of accent marks. These errors are quite frequent when dealing with files. No matter what caused the formatting to break, it is essential that we are able to remove these characters from the string. And python has a few handy inbuilt functions that can be used.

Methods to remove a char form string in python.

character python

While trying to remove a char from a string in python, you should keep in mind that strings are immutable i.e they cannot be changed. So remember to either reassign the updated string to the same variable or store the updated string in a new variable.

Using replace( ):

Replace is one of the most common methods used to remove a char from a string in python. The syntax of replace() is as follows.

Syntax of replace( ):

string.replace(old character, new character, count)


Old char -The char that needs to be replaced

new character – The char you are looking to replace with

count – This is an optional parameter, and is used to specify how many occurrences of the old character you intend to replace

Code to remove a char from string in python using replace( ):

s = "flexible!"
s2 = string.replace("b","p")

// Output - "flexiple!"

//Code to remove a char
s3 =string.replace("!","")

//Output - "flexiple"

In case you are looking to remove multiple chars from a string, you can add all the characters to an iterable, and replace each element with a loop. Also, remember that strings are immutable and you need to assign the updated string to a variable.