How to remove a character from a string in python?

Python Methods and Functions

If you want to remove a character at a specific index from a string, you can use string slicing to create a string without that character. For example,

 & gt; & gt; & gt; s = "Hello World" & gt; & gt; & gt; s [: 4] + s [5:] "Hell World" 

But if you want to remove all occurrences of a character or a list of characters, you can use the following methods:

The string class has a replace method, which can be used to replace substrings in a string. We can use this method to replace the characters we want to remove with an empty string. For example:

 & gt; & gt; & gt; "Hello people" .replace ("e", "") "Hllo popl" 

If you want to remove multiple characters from a string on one line, it is better to use regular expressions. You can strip multiple characters & # 171; | & # 187; and use re.sub (chars_to_replace, string_to_replace_with, str). For example:

 & gt; & gt; & gt; import re & gt; & gt; & gt; re.sub ("e | l", "", "Hello people") "Ho pop" 

Note. You can also use [] to create a group of characters to replace in a regular expression.

Get Solution for free from DataCamp guru