1

I wrote this code in python to remove a group of specific characters from texts. But the code works only for the first type of characters, for instance:

"I live in street 223, Los Angeles and this isn't true :)"

should be:

"i live in street los angeles and this isnt true"

but as the number 2 is before the rest of the characters that should be removed -in the set v- the result that I get instead:

"i live in street 3, los angeles and this isn't true :)"

My code:

v = ["1","2","3","4","5","6","7","8","9","0",".","(",")",',',':',";",'"',"'","?","!","+","=","-","$","#","@","<",">"]

def p(r):
   for e in r:
       if e in v:
           return r.replace(e,"")
       else:
           pass
       
print(p("I live in street 223, Los Angeles and this isn't true :)".lower()))

How to modify this code to remove the rest characters? Or is there a better different code? thanks in advance.

3
  • use regex to replace the digits Commented May 4, 2021 at 13:10
  • you are returning the value of r before it is done looping through array v. instead of return, set r = r.replace(e, "") then after you are through the for loop, return the value of r Commented May 4, 2021 at 13:11
  • check out this link stackoverflow.com/questions/817122/… Commented May 4, 2021 at 13:12

1 Answer 1

2

Just create a new string without the invalid characters:

chars = {"1","2","3","4","5","6","7","8","9","0",".","(",")",',',':',";",'"',"'","?","!","+","=","-","$","#","@","<",">"}

def replace(s):
    buf = ""
    for c in s:
        if c not in chars:
            buf += c
    return buf

print(replace("I live in street 223, Los Angeles and this isn't true :)"))
Sign up to request clarification or add additional context in comments.

5 Comments

Thanks this also worked and added some ideas for me but I think it's a little bit complicated.
@GeorgeNabil This is by far much better than calling replace function for every character in a string. What you are doing is O(n^2) operations instead of O(n), which I suggest.
Oh, thanks a lot after understanding your code and analyze mine I found that your code is really better in all directions. And I used your idea in the project.
@GeorgeNabil If you want to improve it even more, use io.StringIO instead of a string: buf = io.StringIO(); for c in s: if c not in chars: buf.write(c); return buf.getvalue(). This will work even faster due to better memory allocation in the Python internals.
Thanks again for this helpful information. If you can suggest to me good resources for GUI in python (for beginners) please attach the links.

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.