In this short tutorial, we look at why you would need to remove a character from a string in Python and we look at the different methods we can use to achieve this. Show
Table of Contents
Why would you need to remove character from string Python?Strings are arguably the commonly used data type in Python and when used to such an extent you come across a plethora of errors. Out of which the most common ones are the new tab escape sequence \n getting appended to the ending of a string or special characters 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 character from string in PythonWhile trying to remove character from 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. With that out of the way let's look at methods we can use to remove character from string in Python. Using replace():Replace is one of the most common methods used to remove a character from a string in Python. Although, replace() was intended to replace a new character with an older character - using "" as the new character can be used to remove a character from a string. The syntax of replace() is as follows. Syntax of replace(): string.replace(old character, new character, count) string is the positional argument containing the string.Parameters: old character - The character that needs to be replaced new character - The character 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 character from string in Python using replace(): In case you are looking to remove multiple characters 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. Using translate():translate() is another method that can be used to remove a character from a string in Python. translate() returns a string after removing the values passed in the table. Also, remember that to remove a character from a string using translate() you have to replace it with None and not "". Syntax of translate(): string.translate(table)Parameters: table - The values could either be a dictionary or a mapping table that describes what values should be replaced. Code to use translate(): s = "Flexible" x = "b" y = "p" table = s.maketrans(x, y) print(s.translate(table)) #Output - "Flexiple"Although this method can be quite tedious there is a way around it. But before that, you need to familiarize yourself with the below concept. From Python version 3 and above strings are Unicode, which essentially means strings get converted into a Unicode, this helps maintain a uniform code irrespective of the language the programmer uses. You can read more about this here. This is why you are required to pass the variables into a table. But by using the ord() function, this function returns the Unicode of a character. This can be used to remove a character from a string. The code is as follows. Code to remove character from string using translate(): s = 'flexiple!' s1 = s.translate({ord('!'): None}) print(s1) #Output - "flexiple"Remember in order for translate() to remove a character you need to replace it with None. Closing ThoughtsOut of both the methods, I personally find myself using replace() more often than translate() as it is easier to comprehend. Although once you understand how translate() works it again becomes a personal preference. However, remember that strings are Immutable and you need to store the updated string if you intend to use it further. The following methods are used to remove a specific character from a string in Python.
Note that the string is immutable in Python. So the original string remains unchanged and a new string is returned by these methods. 1. Removing a Character from String using the Naive methodIn this method, we have to run a loop and append the characters and build a new string from the existing characters except when the index is n. (where n is the index of the character to be removed) input_str = "DivasDwivedi" # Printing original string print ("Original string: " + input_str) result_str = "" for i in range(0, len(input_str)): if i != 3: result_str = result_str + input_str[i] # Printing string after removal print ("String after removal of i'th character : " + result_str) Output: Original string: DivasDwivedi 2. Removal of Character from a String using replace() Methodstr = "Engineering" print ("Original string: " + str) res_str = str.replace('e', '') # removes all occurrences of 'e' print ("The string after removal of character: " + res_str) # Removing 1st occurrence of e res_str = str.replace('e', '', 1) print ("The string after removal of character: " + res_str) Output: Original string: Engineering The string after removal of character: Enginring The string after removal of character: Enginering 3. Removal of Character from a String using Slicing and Concatenationstr = "Engineering" print ("Original string: " + str) # Removing char at pos 3 # using slice + concatenation res_str = str[:2] + str[3:] print ("String after removal of character: " + res_str) Output: Original string: Engineering 4. Removal of Character from a String using join() method and list comprehensionIn this technique, every element of the string is converted to an equivalent element of a list, after which each of them is joined to form a string excluding the particular character to be removed. str = "Engineering" print ("Original string: " + str) # Removing char at index 2 # using join() + list comprehension res_str = ''.join([str[i] for i in range(len(str)) if i != 2]) print ("String after removal of character: " + res_str) Output: Original string: Engineering 5. Removal of character from a string using translate() methodstr = 'Engineer123Discipline' print(str.translate({ord(i): None for i in '123'})) Output: EngineerDiscipline References
lst = [("aaaa8"),("bb8"),("ccc8"),("dddddd8")...] msg = filter(lambda x : x != "8", lst) print msg EDIT: For anyone who came across this post, just for understanding the above removes any elements from the list which are equal to 8. Supposing we use the above example the first element ("aaaaa8") would not be equal to 8 and so it would be dropped. To make this (kinda work?) with how the intent of the question was we could perform something similar to this msg = filter(lambda x: x != "8", map(lambda y: list(y), lst))
What this does is split each element of list up into an array of characters so ("aaaa8") would become ["a", "a", "a", "a", "8"]. This would result in a data type that looks like this msg = [["a", "a", "a", "a"], ["b", "b"]...] So finally to wrap that up we would have to map it to bring them all back into the same type roughly msg = list(map(lambda q: ''.join(q), filter(lambda x: x != "8", map(lambda y: list(y[0]), lst))))I would absolutely not recommend it, but if you were really wanting to play with map and filter, that would be how I think you could do it with a single line. |