Remove all chars python

How To Remove Characters from a String in Python

How To Remove Characters from a String in Python

This article describes two common methods that you can use to remove characters from a string using Python:

To learn some different ways to remove spaces from a string in Python, refer to Remove Spaces from a String in Python.

A Python String object is immutable, so you can’t change its value. Any method that manipulates a string value returns a new String object.

The examples in this tutorial use the Python interactive console in the command line to demonstrate different methods that remove characters.

Remove Characters From a String Using the replace() Method

The String replace() method replaces a character with a new character. You can remove a character from a string by providing the character(s) to replace as the first argument and an empty string as the second argument.

Declare the string variable:

Replace the character with an empty string:

The output shows that both occurrences of the character a were removed from the string.

Remove Newline Characters From a String Using the replace() Method

Declare a string variable with some newline characters:

Replace the newline character with an empty string:

The output shows that both newline characters ( \n ) were removed from the string.

Remove a Substring from a String Using the replace() Method

The replace() method takes strings as arguments, so you can also replace a word in string.

Declare the string variable:

Replace a word with an empty string:

The output shows that the string Hello was removed from the input string.

Remove Characters a Specific Number of Times Using the replace() Method

You can pass a third argument in the replace() method to specify the number of replacements to perform in the string before stopping. For example, if you specify 2 as the third argument, then only the first 2 occurrences of the given characters are replaced.

Declare the string variable:

Replace the first two occurrences of the character with the new character:

The output shows that the first two occurrences of the a character were replaced by the A character. Since the replacement was done only twice, the other occurrences of a remain in the string.

Remove Characters From a String Using the translate() Method

The Python string translate() method replaces each character in the string using the given mapping table or dictionary.

Читайте также:  Css div positioning fixed

Declare a string variable:

Get the Unicode code point value of a character and replace it with None :

The output shows that both occurrences of the b character were removed from the string as defined in the custom dictionary.

Remove Multiple Characters From a String using the translate() method

You can replace multiple characters in a string using the translate() method. The following example uses a custom dictionary, , that replaces all occurrences of a , b , and c in the given string with None .

Declare the string variable:

Replace all the characters abc with None :

The output shows that all occurrences of a , b , and c were removed from the string as defined in the custom dictionary.

Remove Newline Characters From a String Using the translate() Method

You can replace newline characters in a string using the translate() method. The following example uses a custom dictionary, , that replaces all occurrences of \n in the given string with None .

Declare the string variable:

Replace all the \n characters with None :

The output shows that all occurrences of the newline character \n were removed from the string as defined in the custom dictionary.

Conclusion

In this tutorial, you learned some of the methods you can use to remove characters from strings in Python. Continue your learning about Python strings.

Want to deploy your application quickly? Try Cloudways, the #1 managed hosting provider for small-to-medium businesses, agencies, and developers — for free. DigitalOcean and Cloudways together will give you a reliable, scalable, and hassle-free managed hosting experience with anytime support that makes all your hosting worries a thing of the past. Start with $100 in free credits!

Источник

Python: Remove characters from string by regex & 4 other ways

In this article we will discuss different ways to delete single or multiple characters from string in python either by using regex() or translate() or replace() or join() or filter().

Remove characters from string using regex

Python’s regex module provides a function sub() i.e.

re.sub(pattern, repl, string, count=0, flags=0)

It returns a new string. This new string is obtained by replacing all the occurrences of the given pattern in the string by a replacement string repl. If the pattern is not found in the string, then it returns the same string.

Let’s use this to remove characters from a string,

Frequently Asked:

Remove all occurrences of a character from string using regex

Suppose we want to delete all the occurrences of character ‘s’ from the string. For that we need to pass such a pattern in the sub() function, that matches all the occurrences of character ‘s’ in the given string. Then sub() function should replace all those characters by an empty string i.e.

import re org_string = "This is a sample string" pattern = r's' # Replace all occurrences of character s with an empty string mod_string = re.sub(pattern, '', org_string ) print(mod_string)

It removed all the occurrences of character ‘s’ from the string.

Remove multiple characters from string using regex in python

Suppose we want to delete all the occurrences of character ‘s’, ‘a’ and ‘i’ from the string. For that we need to pass such a pattern in the sub() function, that matches all the occurrences of character ‘s’, ‘a’ & ‘i’ in the given string. Then sub() function should replace all those characters by an empty string i.e.

import re org_string = "This is a sample string" pattern = r'[sai]' # Remove characters 's', 'a' and 'i' from a string mod_string = re.sub(pattern, '', org_string) print(mod_string)

It removed all the occurrences of character ‘s’, ‘a’ and ‘i’ from the string.

Читайте также:  Html span text javascript

Remove characters in list from the string in python.

Suppose we want to delete all the occurrences of character ‘s’, ‘a’ and ‘i’ from the string and all these characters are in a list i.e.

In this case we will create our pattern by joining all characters in the string and the use sub() function to delete these characters from the string,

import re list_of_char = ['s', 'a', 'i'] pattern = '[' + ''.join(list_of_char) + ']' # Remove characters matched by pattern mod_string = re.sub(pattern, '', org_string) print(mod_string)

It removed all the occurrences of character ‘s’, ‘a’ and ‘i’ from the string.

Remove characters from string using translate()

In python, str class provides a function translate(table). It replaces the characters in string based on the mapping provided in the translation table. Let’s use this to remove single or multiple characters from string,

Remove all occurrence of a character from the string using translate()

Suppose we want to delete all occurrences of character ‘s’ from the string. For that we will pass a translation table to the translate() function. In the translation table, character ‘s’ will be mapped to None i.e.

org_string = "This is a sample string" # Remove all occurrence of a character 's' from the string mod_string = org_string.translate() print(mod_string)

It will replaced all the occurrences of character ‘s’ with None in the string i.e. it removed all occurrences of character ‘s’ from the string.

Remove multiple characters from the string using translate()

Suppose we want to delete all occurrences of character ‘s’, ‘a’ & ‘i’ from the string. For that we will pass a translation table to the translate() function, where characters ‘s’, ‘a’ & ‘i’ will be mapped to None i.e.

list_of_char = ['s', 'a', 'i'] # Remove all occurrence of a characters 's', 'a' & 'i' from the string mod_string = org_string.translate( ) print(mod_string)

It will remove all occurrences of characters ‘s’, ‘a’ & ‘i’ from the string.

Remove characters from string using replace()

In Python, str class provides a function replace() i.e.

It returns a copy of string by replacing all occurrences of sub_string with repl.

Let’s use to remove all occurrence of a character ‘s’ from the string,

org_string = "This is a sample string" # Remove all occurrence of a character 's' from the string mod_string = org_string.replace('s', '') print(mod_string)

Remove characters from string using join() and generator expression

Suppose we have a list of characters i.e.

Now to remove all occurrences of these characters from the string. We can iterate over each character in the string and join them back except the characters which are in list i.e.

list_of_char = ['s', 'a', 'i'] # Remove all characters in list, from the string mod_string = ''.join((elem for elem in org_string if elem not in list_of_char)) print(mod_string)

It removed all occurrences of characters ‘s’, ‘a’ & ‘i’ from the string.

Читайте также:  Перенос строки питон print

Remove characters from string using join and filter()

Instead of filtering characters using a for loop and generator expression, we can filter them using filter() function and then join back all filtered characters i.e.

org_string = "This is a sample string" list_of_char = ['s', 'a', 'i'] # Remove all characters in list, from the string mod_string = ''.join(filter(lambda k: k not in list_of_char, org_string)) print(mod_string)

It filtered the characters from the string based on logic provided as call back function. As the call-back function, we provided a lambda function which checked if character is in list of filtered characters or not. Then joined the remaining characters to create a new string. So basically, it removed all occurrences of characters ‘s’, ‘a’ & ‘i’ from the string.

These were the different ways to remove characters from a string.

The complete example is as follows,

import re def main(): print('****** Remove characters from string by regex ******') print('*** Remove all occurrences of a character from string using regex ***') org_string = "This is a sample string" pattern = r's' # Replace all occurrences of character s with an empty string mod_string = re.sub(pattern, '', org_string ) print(mod_string) print('*** Remove multiple characters from string using regex ***') org_string = "This is a sample string" pattern = r'[sai]' # Remove characters 's', 'a' and 'i' from a string mod_string = re.sub(pattern, '', org_string) print(mod_string) print('*** Python remove characters in list from the string ***') list_of_char = ['s', 'a', 'i'] pattern = '[' + ''.join(list_of_char) + ']' # Remove characters matched by pattern mod_string = re.sub(pattern, '', org_string) print(mod_string) print('*** Remove characters from string using translate()***') org_string = "This is a sample string" # Remove all occurrence of a character 's' from the string mod_string = org_string.translate() print(mod_string) org_string = "This is a sample string" list_of_char = ['s', 'a', 'i'] # Remove all occurrence of a characters 's', 'a' & 'i' from the string mod_string = org_string.translate(< ord(elem): None for elem in list_of_char>) print(mod_string) print('*** Remove a character from string using replace()***') org_string = "This is a sample string" # Remove all occurrence of a character 's' from the string mod_string = org_string.replace('s', '') print(mod_string) print('*** Remove multiple character from string using join() ***') org_string = "This is a sample string" list_of_char = ['s', 'a', 'i'] # Remove all characters in list, from the string mod_string = ''.join((elem for elem in org_string if elem not in list_of_char)) print(mod_string) print('****** Remove multiple characters from string using filter() ******') org_string = "This is a sample string" list_of_char = ['s', 'a', 'i'] # Remove all characters in list, from the string mod_string = ''.join(filter(lambda k: k not in list_of_char, org_string)) print(mod_string) if __name__ == '__main__': main()
****** Remove characters from string by regex ****** *** Remove all occurrences of a character from string using regex *** Thi i a ample tring *** Remove multiple characters from string using regex *** Th mple trng *** Python remove characters in list from the string *** Th mple trng *** Remove characters from string using translate()*** Thi i a ample tring Th mple trng *** Remove a character from string using replace()*** Thi i a ample tring *** Remove multiple character from string using join() *** Th mple trng ****** Remove multiple characters from string using filter() ****** Th mple trng

Источник

Оцените статью