0

I’m trying to optimize my code. I have a list of strings that have quite a few characters I don’t want. Rather than just call

My_string.replace(‘!’, ‘’).replace(‘$’, ‘’)…

I was hoping for a more elegant solution. I have probably 50-60 characters that need to be removed. I do need to use pairs somehow because not every character is being replaced with nothing.

Pat
  • 81
  • 4
  • 2
    Please pay extremely close attention to the types of quotes you're using. – tadman Aug 22 '23 at 18:51
  • 1
    Does this answer your question? [Character Translation using Python (like the tr command)](https://stackoverflow.com/questions/555705/character-translation-using-python-like-the-tr-command) If you're simply removing them instead of substituting, consider a regular expression. – tadman Aug 22 '23 at 18:51

1 Answers1

0

first of all those quotes are misleading, so I'll use the standard ones. You can create a translation table using the str.maketrans method and then use str.translate.

something like this:

# Define a dictionary with characters to be replaced as keys and their replacements as values 
# ('char to substitute': 'substitution')

replace_chars = {
    '!': '',
    '$': 's',
    # Add more characters and replacements here
}

# Create a translation table
translation_table = str.maketrans(replace_chars)

my_string = "Your input $tring!"

# Use translate to remove/replace characters
cleaned_string = my_string.translate(translation_table)

Francesco
  • 171
  • 8