简体   繁体   中英

I want to replace a special character with a space

Here is the code i have until now :

dex = tree.xpath('//div[@class="cd-timeline-topic"]/text()')
names = filter(lambda n: n.strip(), dex)
table = str.maketrans(dict.fromkeys('?:,'))
for index, name in enumerate(dex, start = 0):

print('{}.{}'.format(index, name.strip().translate(table)))

The problem is that the output will print also strings with one special character "My name is/Richard". So what i need it's to replace that special character with a space and in the end the printing output will be "My name is Richard". Can anyone help me ?

Thanks!

Your call to dict.fromkeys() does not include the character / in its argument.

If you want to map all the special characters to None , just passing your list of special chars to dict.fromkeys() should be enough. If you want to replace them with a space, you could then iterate over the dict and set the value to for each key.

For example:

special_chars = "?:/"
special_char_dict = dict.fromkeys(special_chars)
for k in special_char_dict:
    special_char_dict[k] = " "

You can do this by extending your translation table:

dex = ["My Name is/Richard????::,"]
table = str.maketrans({'?':None,':':None,',':None,'/':' '})
for index, name in enumerate(dex, start = 0):

    print('{}.{}'.format(index, name.strip().translate(table)))

OUTPUT

0.My Name is Richard

You want to replace most special characters with None BUT forward slash with a space. You could use a different method to replace forward slashes as the other answers here do, or you could extend your translation table as above, mapping all the other special characters to None and forward slash to space. With this you could have a whole bunch of different replacements happen for different characters.

Alternatively you could use re.sub function following way:

import re
s = 'Te/st st?ri:ng,'
out = re.sub(r'\?|:|,|/',lambda x:' ' if x.group(0)=='/' else '',s)
print(out) #Te st string

Arguments meaning of re.sub is as follows: first one is pattern - it informs re.sub which substring to replace, ? needs to be escaped as otherwise it has special meaning there, | means: or, so re.sub will look for ? or : or , or / . Second argument is function which return character to be used in place of original substring: space for / and empty str for anything else. Third argument is string to be changed.

>>> a = "My name is/Richard"
>>> a.replace('/', ' ')
'My name is Richard'

To replace any character or sequence of characters from the string, you need to use `.replace()' method. So the solution to your answer is:

name.replace("/", " ")

here you can find details

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM