1

I am looking for a way to replace a characters in a sentence, given that we have:

sentence = "hello - world!: ¡hola - mundo"

I need to be it like that -> hello world hola mundo

I can do

sentence.replace('!' , '' )
sentence.replace(':' , '' )
.
.
.

But it doesn't seems a good solution

so far i have this, but it doesn't replace what I want:

for ch in ["!",":"]:
        if ch in sentence:
            sentence = sentence.replace(ch," " + ch)

any suggestions how to make it work? Thank you.

Mike McKerns
  • 33,715
  • 8
  • 119
  • 139
b8ckwith
  • 95
  • 9
  • 1
    There's a good discussion of this here: http://stackoverflow.com/questions/10017147/python-replace-characters-in-string – nofinator Nov 05 '14 at 17:16

2 Answers2

0

You can make a set of all characters you want to keep, then use a generator expression to keep all those letters. Or conversely a set of characters to be removed and keep everything but those. The string library has some useful things for this, e.g. string.ascii_lowercase or string.punctuation.

>>> import string
>>> keep = set(string.ascii_lowercase + string.ascii_uppercase + ' ')

>>> ''.join(i for i in sentence if i in keep)
'hello  world hola  mundo'
Cory Kramer
  • 114,268
  • 16
  • 167
  • 218
0

you can split your sentence with none alphabet characters and join those that have len>0 for refuse '':

>>> import re
>>> ' '.join([i for i in re.split(r'\W',sentence) if len(i)])
'hello world hola mundo'
Mazdak
  • 105,000
  • 18
  • 159
  • 188