1

Let's say I have multiple strings:

string1 = "ab"
string2 = "db"
string3 = "eb"

How do I replace the same substring in all of them? Let's say I need to replace"b" with "c". I can sure do the following, but is there a neat one-line solution?

string1 = string1.replace("b", "c")
string2 = string2.replace("b", "c")
string3 = string3.replace("b", "c")
1
  • 4
    sounds to me like you want to store your strings in a data structure like a list rather than keeping them all as individual variables; then you can just do strings = [string.replace("b", "c') for string in strings] Commented Sep 7, 2017 at 23:41

2 Answers 2

3
string1,string2,string3=[string.replace('b','c') for string in [string1,string2,string3]]

Try this neat list comprehension one-liner

Sign up to request clarification or add additional context in comments.

Comments

1

You can use a class and create classmethods in list comprehension:

class String:
   def __init__(self, s):
       self.s = s
   def replace(self, old, new):
      return self.s.replace(old, new)


string1 = "ab"
string2 = "db"
string3 = "eb"
l = [String(i).replace("b", "c") for i in [string1, string2, string3]]

Output:

['ac', 'dc', 'ec']

1 Comment

what is advantage of using class in this example?

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.