3

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, "")
kederrac
  • 16,819
  • 6
  • 32
  • 55
  • Does this answer your question? [Remove specific characters from a string in Python](https://stackoverflow.com/questions/3939361/remove-specific-characters-from-a-string-in-python) – Querenker Mar 25 '20 at 20:31

3 Answers3

2

figured it out:

def remove_specialchr(string):
    unwanted_specialchr = [',', '.', '"', '\'', ':',]
    for chr in string:
        if chr in  unwanted_specialchr:
            string = string.replace(chr, '')
    return string
  • 1
    You can get a speedup out of this by converting `unwanted_specialchr` to a set. Replace the square brackets with curly braces. It still may not be optimal, because you have to do O(len(unwanted_specialchar)) `replace` operations, which pass over the entire string. – Arya McCarthy Mar 26 '20 at 13:51
1

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!'
kederrac
  • 16,819
  • 6
  • 32
  • 55
1

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
Mandy007
  • 421
  • 7
  • 18