1

Let's have a variable string defined as:

string = "5+--+-+-+-+--+++---++-+-+-+-5"

What is the best way to replace all "++" by "+", all "--" by "+" and all "-+" and "+-" by "-", to get:

string = "5+5"

I thought about:

from re import sub

while True:
    if "-+" not in string and "+-" not in string and "++" not in string and "--" not in string:
        break
    string = sub("\++", "+", string).replace("--", "+").replace("+-", "-").replace("-+", "-")

Is it the best way to do it?

TheOneMusic
  • 1,776
  • 3
  • 15
  • 39
  • 1
    You are using both sub and replace. You need only the latter. Perhaps if you share the backgroung to how this string came to be we can give even better advice. – Vitaliy Jul 27 '19 at 18:45
  • 1
    Related but not a duplicate: https://stackoverflow.com/q/6116978/102441 – Eric Jul 27 '19 at 19:29

1 Answers1

4

It looks a bit wierd, but it works

string = "5+--+-+-+-+--+++---++-+-+-+-5"
old = s = string
while True:
    s = s.replace("++", "+").replace("--", "+").replace("-+", "-").replace("+-", "-")
    if old == s:
        break
    old = s

print(s)

You could also create a dictionary for all replacement rules and iterate over it instead of explicitly calling replace multiple times.

string = "5+--+-+-+-+--+++---++-+-+-+-5"
old = s = string

repl = {
    "++": "+",
    "--": "+",
    "-+": "-",
    "+-": "-"
}

while True:
    for key, value in repl.items():
        s = s.replace(key, value)
    if old == s:
        break
    old = s

print(s)
Saritus
  • 918
  • 7
  • 15
  • Thank you, which method is the best based on your opinion? – TheOneMusic Jul 27 '19 at 18:50
  • 1
    Since you have only 4 replacement rules, i would prefer the first one, but if you want to add more (in the future), the second one is definitely more suitable. – Saritus Jul 27 '19 at 18:54
  • 2
    2 looks better to me. If the number of lines is driving your decision, just wrap the dictionary onto one line - it's no worse than having the `.replace` calls all on one line in the first example – Eric Jul 27 '19 at 19:31