Using a List as 1 argument in replace()

Viewed 791

Trying to solve.

I have a string from a user input. And I want to reomove all special characters from a list = [',', '.', '"', '\'', ':',]

using the replace function I´m able to remove one by one. using somethin like:

string = "a,bhc:kalaej jff!"
string.replace(",", "")

but I want to do remove all the special chr. in one go. I have tried:

unwanted_specialchr = [',', '.', '"', '\'', ':',]
string = "a,bhc:kalaej jff!"
string.replace(unwanted_specialchr, "")
3 Answers

you can use re.sub:

import re

unwanted_specialchr = [',', '.', '"', '\'', ':',]
string = "a,bhc:kalaej jff!"
re.sub(f'[{"".join(unwanted_specialchr)}]', '', string)

output:

'abhckalaej jff!'

or you could use:

''.join(c for c in string if c not in unwanted_specialchr)

output:

'abhckalaej jff!'

figured it out:

def remove_specialchr(string):
    unwanted_specialchr = [',', '.', '"', '\'', ':',]
    for chr in string:
        if chr in  unwanted_specialchr:
            string = string.replace(chr, '')
    return string

Well i think that your solution could be better with the optimization:

def remove_specialchr(string):
    specialChr = {',', '.', '"', '\'', ':'}
    stringS = ''
    for chr in string:
        if chr not in specialChr:
            stringS += it
    return stringS
Related