Compare and replace items in a row

I am looking for help on a problem that made me stop. I have a few lines that look like this:

line = '{2}*{3}^2'

The numbers in braces have a display in the dictionary, where the dictionary will look something like this:

factorseq_dict = [('2', 'NAME1'), ('3', 'NAME2')]

What I'm looking for is a script that will read every key (numbers in brackets) in a string and look for the corresponding value in the dictionary. This value will be used to create a new mylist, while preserving everything else in the original string constant. So my new content will change line to new line as follows.

line = '{2}*{3}^2'
newline = '{NAME1}*{NAME2}^2'

I have a dictionary created, but really struggling with the rest of the logic, because I cannot separate the elements that are in curly brackets with the usual numbers, so I am sorry that I can not provide an example code.

, ,

line='{2}*{3}^2'
elements = re.split('({[^}]*})', line)

+4
1

re.sub.

>>> import re
>>> line = '{2}*{3}^2'
>>> factorseq_dict = [('2', 'NAME1'), ('3', 'NAME2')]
>>> dict_ = dict(factorseq_dict)
>>> re.sub(r'\{(\d+)\}', lambda m: '{' + dict_[m.group(1)] + '}', line)
'{NAME1}*{NAME2}^2'

re.sub -

dict_ = {'3': 'NAME2', '2': 'NAME1'}

pattern r '{(\ d +)}' '2' '3' dict_, . dict _ ['2'] "NAME1" ( {NAME1} ..), line {2} {3}. , '{NAME1} * {NAME2} ^ 2'

+3

Source: https://habr.com/ru/post/1613960/


All Articles