Search code examples
pythonregexstringreplacestrip

How to remove characters from string?


How to remove user defined letters from a user defined sentence in Python?

Hi, if anyone is willing to take the time to try and help me out with some python code.

I am currently doing a software engineering bootcamp which the current requirement is that I create a program where a user inputs a sentence and then a user will input the letters he/she wishes to remove from the sentence.

I have searched online and there are tons of articles and threads about removing letters from strings but I cannot find one article or thread about how to remove user defined letters from a user defined string.

import re
sentence = input("Please enter a sentence: ")
letters = input("Please enter the letters you wish to remove: ")
sentence1 = re.sub(letters, '', sentence)
print(sentence1)

The expected result should remove multiple letters from a user defined string, yet this will remove a letter if you only input 1 letter. If you input multiple letters it will just print the original sentence. Any help or guidance would be much appreciated.


Solution

  • >>> sentence1 = re.sub(str([letters]), '', sentence)
    

    Preferably with letters entered in the form letters = 'abcd'. No spaces or punctuation marks if necessary.

    .

    Edit:

    These are actually better:

    >>> re.sub('['+letters+']', '', sentence)
    >>> re.sub('['+str(letters)+']', '', sentence)
    

    The first also removes \' if it appears in the string, although it is the prettier solution