Home > Net >  Is there a reverse "fstring"?
Is there a reverse "fstring"?

Time:02-04

I need to find a way to call a way to use something with fstring syntax to retrieve information from a string.

My goal is to use the same fstring to create a string, and then decode it.

For example:

def encode():
    a = "fizz"
    b = "buzz"
    return f"{a} / {b}"

def decode(my_string: str):
    a = ""
    b = ""
    f"{a} / {b}" # Something like that, more or less.
    print(a) # fizz
    print(b) # buzz

I know this example is stupid, but I really need something like that. I work with a proprietary testing software that allow me to call python script, but these scripts can only return values to the software by writing to stdout. And, then, I want to retrieve them in another script called further.


I know there is a possibility to retrieve it with regex, but I want to have the same "fstring" for both functions, to avoid duplication.

CodePudding user response:

def encode():
    a = "fizz"
    b = "buzz"
    return f"{a}/{b}"

def decode(my_string: str,d="/"):
    a,b = my_string.split(d)
    print(a) # fizz
    print(b) # buzz

CodePudding user response:

To a certain degree this is possible if you can make restrictions to your arguments a and b and your string. E.g. if your string always has the form f"{a} / {b}" and no " / " appears in a or b you can use that information:

def encode(a, b):
    return f"{a} / {b}"

def decode(my_str: str):
    return my_str.split(" / ")


a = "fizz"
b = "buzz"

my_str = encode(a, b)
dec_a, dec_b = decode(my_str)
print(dec_a, dec_b)

CodePudding user response:

You should split using your delimiter, in this case it was "/". So do the following:

def decode(myString: str, delimiter="/"):
    a,b = muString.split(delimiter)
    print(f"{a}/{b}")

CodePudding user response:

You can, to some extent, turn it on its head and have a "reverse regular expression". It works by parsing the regular expression with another regular expression (yikes!):

import re

pattern = r'(?P<a>.*?) / (?P<b>.*?)'

def format_re(regexp, **kwargs):
    def replace_fn(match):
        return kwargs[match.group('group_name')]
    return re.sub(
        r'\(\?P<(?P<group_name>.*?)>.*?\)',
        replace_fn,
        pattern)

def encode(a, b):
    return format_re(pattern, a=a, b=b)

def decode(my_string):
    match = re.match('^'   pattern   '$', my_string)
    return match.group('a'), match.group('b')

print(encode('fizz', 'buzz')) # fizz / buzz
print(decode('fizz / buzz'))  # ('fizz', 'buzz')

Of course, unnamed, nested and repeated groups will cause trouble, and so will regex metacharacters outside capture groups. And I'm sure there are other problems with it that I don't care to think about right now.

I don't think all this overhead is better than the very slight amount of duplication, but there you have it.

  •  Tags:  
  • Related