-1
def rm_char(text,x):
    return text.replace(x,'')

I am very new to python, How can I improve this function so I can remove multiple characters from text,i.e allow function to take more than "character" to be removed from text and replace it with ""

Piggydog
  • 21
  • 1
  • 6
  • Call the function as many times as the number of different characters you need to replace passing them one at a time in each call. (may not feel pythonic but just a way) – Austin Sep 26 '19 at 17:04
  • @Austin I am better off just using `replace` multiple times which is not pythonic – Piggydog Sep 26 '19 at 17:04
  • @Piggydog using `replace` several time is not per se not pythonic. But if what you are searching is for your code to be pythonic, you could check out Python Tricks: The book. And get a couple tutorials about python language specifics, such as comprehension lists (proposed in answer). You should also follow Prunes advice and dig a little bit more the web, and elaborate a bit more on questions. – MikeMajara Sep 26 '19 at 17:10
  • @MikeMajara I found some answers on this, they were mostly based on python 2,7 I thought there was a newer way or at least one regex answer – Piggydog Sep 26 '19 at 17:13
  • @Piggydog you can find plenty on stuff on this issue online. Just dig a little deeper. I added a regex solution too just in case it was what you where looking for. [This](https://stackoverflow.com/questions/3411771/best-way-to-replace-multiple-characters-in-a-string) can help you with performance, and [here](https://stackoverflow.com/questions/16720541/python-string-replace-regular-expression) you can check other questions that already exist regarding this issue. – MikeMajara Sep 26 '19 at 17:23

3 Answers3

0

With a comprehension list

def rm_char(text,list_to_remove):
    return "".join([x for x in text if x not in list_to_remove])

With a regex

import re

def rm_char(text,list_to_remove): 
    return re.sub("["+list_to_remove+"]", '', text)
Ole
  • 13
  • 3
MikeMajara
  • 922
  • 9
  • 23
0

You could do something like this:

def rm_chars(text, chars_to_replace):
    for char_to_replace in chars_to_replace:
        text = text.replace(char_to_replace, '')

    return text

text = "hello"
chars_to_replace = ["l", "o"]

new_text = rm_chars(text, chars_to_replace)
print(new_text)

"he"
snejus
  • 43
  • 1
  • 4
0
x_list = ['a','hello']
text = 'hello World a'

def rm_char(text,x_list):
    for x in x_list:
        text.replace(x,'')
    return text

For Loop replaces the elements from the list (x_list) with nothing (deletes them)

Ole
  • 13
  • 3
  • 4
    Please don't post only code as answer, but include an explanation what your code does and how it solves the problem of the question. Answer with an explanation are generally of higher quality, and more likely to attract upvotes. – Mark Rotteveel Sep 26 '19 at 17:51