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, "")
1

3 Answers 3

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
Sign up to request clarification or add additional context in comments.

1 Comment

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.
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!'

3 Comments

when i try to define a code using def code(): I cant get it to return the editet string, any tips?
Do you want to write a function?
you should have a return statement to return something 0_O
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

1 Comment

But it has to construct a new string every time you do a +=. Python strings are immutable.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.