0

I need use regexp with f-string, for simple code:

import re

def double_swap(txt, c1, c2):

result = [re.sub(fr'[{a}]', c1, c2) if a == c1 else (
   re.sub(fr'[{a}]', c2, c1) if a == c2 else a) for a in txt]
return ''.join(result)

results:

print(double_swap("aabbccc", "a", "b"))  # -> bbaaccc
print(double_swap("**##**", "*", "#"))  # -> ##**##

This code is working on vscode and py 3.7.3, but not working on server, I still have problem:

ERROR:   File "<string>", line 12
    result = [re.sub(fr'[{a}]', c1, c2) if a == c1 else (
                             ^
SyntaxError: invalid syntax

Maybe on server is old version of py?

cs95
  • 379,657
  • 97
  • 704
  • 746
mabrix
  • 35
  • 5
  • The only thing I see wrong with your code is your indentation? Perhaps you're not using python3.6. – cs95 Apr 28 '20 at 08:41
  • Just use `format`, `r'[{}]'.format(a)` to check that. But mind that if you pass ``\`` or `^` there,you will get an error. You need to use `a.replace("\\", "\\\\").replace("^", r"\^")` – Wiktor Stribiżew Apr 28 '20 at 08:41
  • 2
    Did you check what the version on the server *is* before asking this? – jonrsharpe Apr 28 '20 at 08:42
  • @WiktorStribiżew or [`.escape`](https://docs.python.org/3/library/re.html#re.escape) it. – jonrsharpe Apr 28 '20 at 08:43
  • @jonrsharpe Yeah, but *I* know what to escape and what does not have to be escaped. `re.escape` escapes all non-word chars. – Wiktor Stribiżew Apr 28 '20 at 08:44
  • What is your question? "Maybe on server is old version of py?" - only you can answer that for sure. "I need use regexp with f-string" - then we can't provide alternatives. – MisterMiyagi Apr 28 '20 at 08:47

0 Answers0