1

I want to replace multiple substrings in a single string, and I want to know what approach is most efficient / best practice.

I've tried using str.replace() and it works but that seems inefficient. I'm running Python 3.6, so I'd like a solution compatible with that.

For some context here, I want to create the name of a (new) class from some text I read. So I need to convert text to (strings for) valid Python identifiers (e.g., "bad-Classname's" becomes "badClassnames"). So while my question of the best way to replace multiple substrings in a single string still stands, if there is a better way to convert text to class names I'd be happy to hear that too.

My existing code is as follows:

my_str = my_str.replace(" ", "").replace(",", "").replace("/", "").replace("'", "").replace("-", "").replace("’", "")

Is there a better way to do this? Regular expressions, a for loop, some builtin string method that I didn't know about?

3 Answers 3

2

Shortly with regexp substitution:

import re

my_str = "bad-Classname's"
my_str = re.sub(r"[ ,/'’-]", "", my_str)
print(my_str)   # badClassnames

  • [ ,/'’-] - regex character class, matches a single character in the list ",/'’-"
Sign up to request clarification or add additional context in comments.

Comments

2

use str.translate()

# this line builds the translation table
# and can be done once
table = str.maketrans({c:'' for c in " ,/'-’"})

my_str = "bad-Classname's"

# this line does the replacement
my_str = my_str.translate(table)

print(my_str)   
# >>> badClassnames

Comments

0

You can use something like this:

string = 'this is a test string'
items_to_remove = ['this', 'is', 'a', 'string']

In [1]: [x for x in string.split() if x not in {'is', 'this', 'a', 'string'}]
Out[1]: ['test']

Hope this answers your query.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.