Replacing Special Characters in a List in Python

Replacing special characters in a list in Python

you could use strip(), as:

file_stuff = map(lambda s: s.strip(), file_stuff)
print(file_stuff)
// ['John Smith', '', 'Gardener', '', 'Age 27', '', 'Englishman']

use filter if you want to remove empty items from list, like

file_stuff = filter(None, map(lambda s: s.strip(), file_stuff))

How can I remove special characters from a list of elements in python?

Use the str.translate() method to apply the same translation table to all strings:

removetable = str.maketrans('', '', '@#%')
out_list = [s.translate(removetable) for s in my_list]

The str.maketrans() static method is a helpful tool to produce the translation map; the first two arguments are empty strings because you are not replacing characters, only removing. The third string holds all characters you want to remove.

Demo:

>>> my_list = ["on@3", "two#", "thre%e"]
>>> removetable = str.maketrans('', '', '@#%')
>>> [s.translate(removetable) for s in my_list]
['on3', 'two', 'three']

Python - replace not working on special character in a list

Look at the construction element:

[i for i in lista if ...

You check the isalpha suitability of the string, but what you keep for your list is the original value of i !

Instead, you want to keep the altered value of i; just do any existing replacements, and forget the isalpha check entirely.

[i.replace("\{", "-").replace("\xad", "-").replace("\xa", "-") for i in lista]

Note that, if there are no occurrences of the special chars in the string, you simply get the original in your final list.

Replace special characters in a string in Python

str.replace is the wrong function for what you want to do (apart from it being used incorrectly). You want to replace any character of a set with a space, not the whole set with a single space (the latter is what replace does). You can use translate like this:

removeSpecialChars = z.translate ({ord(c): " " for c in "!@#$%^&*()[]{};:,./<>?\|`~-=_+"})

This creates a mapping which maps every character in your list of special characters to a space, then calls translate() on the string, replacing every single character in the set of special characters with a space.



Related Topics



Leave a reply



Submit