Home > database >  Multiple replacements
Multiple replacements

Time:02-05

I want the user to be able to input more than one character they want to remove. It works but only if one character is entered.

string = input("Please enter a sentence: ")
removing_chars = input("Please enter the characters you would like to remove: ")
replacements = [(removing_chars, "")]

for char, replacement in replacements:
    if char in string:
        string = string.replace(char, replacement)

print(string)

CodePudding user response:

The issue is that you're treating removing_chars as if it is always a single character.

For example, if removing_chars is 'abc', then replacements will be [('abc', '')], when it should be [('a', ''), ('b', ''), ('c', '')] instead.

To fix this, try using a list comprehension to loop over each character in removing_chars and create a replacement tuple. Like this:

string = input("Please enter a sentence: ")
removing_chars = input("Please enter the characters you would like to remove: ")
replacements = [(char, "") for char in removing_chars]

for char, replacement in replacements:
    if char in string:
        string = string.replace(char, replacement)

print(string)

CodePudding user response:

when you loop over replacements, char takes removing_chars as value. Then, when you check if char in string, Python checks if removing_chars is a substring of string. To actually remove the characters separately, you have to loop over removing_chars in order to get the individual characters.

CodePudding user response:

I would use a combo of maketrans & translate :

string = input("Please enter a sentence: ")
removing_chars = input("Please enter the characters you would like to remove: ")
​
out = string.translate(str.maketrans("", "", removing_chars))

​ Output :

print(out)

#Please enter a sentence:  StacxkOverfLlow
#Please enter the characters you would like to remove:  xL
#StackOverflow

CodePudding user response:

This may be an excellent place to use regular expressions. We can insert the characters to remove string into aa string wrapped in [ and ] to create a character class, and then use sub to replace any occurrences of those characters with ''.

>>> import re
>>> s = input("line of text: ")
line of text: hello world foo bar baz
>>> r = input("characters to remove: ")
characters to remove: abc
>>> rx = re.compile(rf"[{r.strip()}]")
>>> rx
re.compile('[abc]')
>>> rx.sub('', s)
'hello world foo r z'

Of course, to avoid issues with special characters that are significant in regular expression character classes, you may wish to use re.escape. E.g.

>>> rx = re.compile(rf"[{re.escape('a-c')}]")
>>> rx
re.compile('[a\\-c]')
  • Related