-1

is there a function in python that does something like this:

input:

text = "s.om/e br%0oken tex!t".remove(".","/","%","0","!")
print(text)

output:

some broken text

The only thing that i know that can kinda to this is .replace("x", "") and that takes way too long to get rid of lots of different charicters. Thanks in advance.

Rallph
  • 19
  • 1
  • 4
  • 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) – lachy Mar 31 '20 at 08:30

3 Answers3

2

Use regex module re to replace them all. The [] means any character in it :

text = re.sub("[./%0!]", "", "s.om/e br%0oken tex!t")
azro
  • 53,056
  • 7
  • 34
  • 70
  • Sorry, my typing speed is a bit slow I was writing my answer while yours got posted now what to do about my answer? – Wasif Mar 31 '20 at 08:08
  • @WasifHasan You can keep it, there lots of posts where multiple answers are same, or delete it, as you wish – azro Mar 31 '20 at 08:10
0

You might use str.maketrans combined with .translate; example:

t = str.maketrans("","","./%0!")
text = "s.om/e br%0oken tex!t"
cleantext = text.translate(t)
print(cleantext)  # print(cleantext)

maketrans accept 3 arguments, every n-th character from first will be replaced with n-th character from second, all characters present in third will be jettisoned. In this case we only want to jettison so 1st and 2nd arguments are empty strs.

Alternatively you might use comprehension as follows:

text = "s.om/e br%0oken tex!t"
cleantext = ''.join(i for i in text if i not in "./%0!")
print(cleantext)  # some broken text
Daweo
  • 31,313
  • 3
  • 12
  • 25
  • The answer is correct, but I'd say this is not the goal of translate, `re.sub` is much more dedicated ;) – azro Mar 31 '20 at 08:10
  • @azro: do as you wish but remember that even inside `[` and `]` some characters have special meaning for `re.sub`, so do *not* be surprised if after trying to remove `^.` everything excluding `.` will be gone – Daweo Mar 31 '20 at 08:17
  • Thanks for you concern I know regex syntax pretty well ;) – azro Mar 31 '20 at 08:19
0

There is a module named re which is used in Regular expressions. You can use its sub function to replace or substitute characters from a string. Then you can try like this:

from re import sub
text = sub("[./%0!]","","The string")
print(text)

Regex details: Character class of . / % 0 ! if these are found in string replace them with a blank string and later print the text variable.

Wasif
  • 14,755
  • 3
  • 14
  • 34