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.

1 Answers1

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 :)"))
VisioN
  • 143,310
  • 32
  • 282
  • 281
  • Thanks this also worked and added some ideas for me but I think it's a little bit complicated. – George Nabil May 04 '21 at 13:27
  • @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. – VisioN May 04 '21 at 14:11
  • 1
    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. – George Nabil May 04 '21 at 15:51
  • @GeorgeNabil If you want to improve it even more, use [`io.StringIO`](https://docs.python.org/3/library/io.html#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. – VisioN May 04 '21 at 16:55
  • Thanks again for this helpful information. If you can suggest to me good resources for GUI in python (for beginners) please attach the links. – George Nabil May 04 '21 at 17:21