Regex to replace %variables%

2024/10/2 16:30:22

I've been yanking clumps of hair out for 30 minutes doing this one...

I have a dictionary, like so:

{'search': 'replace','foo':    'bar'}

And a string like this:

Foo bar %foo% % search %.

I'd like to replace each variable with it's equivalent text from the dictionary:

Foo bar bar replace.

My current regex fails, so here it is (key and value are from dictionary.items()):

 re.sub(r'%\d+' + key + '[^%]\d+%', value, text)

Any help would be appreciated, as this regex stuff is driving me nuts...

Answer

If you're flexible with your syntax in your string, Python has a built in mechanism for that:

>>> print 'Hello, %(your_name)s, my name is %(my_name)s' % {'your_name': 'Blender', 'my_name': 'Ken'}
Hello, Blender, my name is Ken

Alternatively, if you want that syntax, I'd avoid regular expressions and just do this:

>>> vars = {'search': 'replace',
...  'foo':    'bar'}
>>> mystring = "Foo bar %foo% % search %."
>>> for k, v in vars.items():
...     mystring = mystring.replace('%%%s%%' % k, v)
... 
>>> print mystring
Foo bar bar % search %.
https://en.xdnf.cn/q/70828.html

Related Q&A

Python kivy - how to reduce height of TextInput

I am using kivy to make a very simple gui for an application. Nothing complex, very simple layout.Nevertheless I am having a hard time with TextInputs...They always display with full height and I cant …

Python-Matplotlib boxplot. How to show percentiles 0,10,25,50,75,90 and 100?

I would like to plot an EPSgram (see below) using Python and Matplotlib. The boxplot function only plots quartiles (0, 25, 50, 75, 100). So, how can I add two more boxes?

Python Pandas reads_csv skip first x and last y rows

I think I may be missing something obvious here, but I am new to python and pandas. I am reading a large text file and only want to use rows in range(61,75496). I can skip the first 60 rows withkeyword…

Combine two arrays data using inner join

Ive two data sets in array: arr1 = [[2011-10-10, 1, 1],[2007-08-09, 5, 3],... ]arr2 = [[2011-10-10, 3, 4],[2007-09-05, 1, 1],... ]I want to combine them into one array like this: arr3 = [[2011-10-10, 1…

How to change fontsize of individual legend entries in pyplot?

What Im trying to do is control the fontsize of individual entries in a legend in pyplot. That is, I want the first entry to be one size, and the second entry to be another. This was my attempt at a so…

Split array into equal sized windows [duplicate]

This question already has answers here:Sliding window of M-by-N shape numpy.ndarray(8 answers)Closed 10 months ago.I am trying to split an numpy.array of length 40 into smaller, equal-sized numpy.array…

Is there a way to send a click event to a window in the background in python?

So Im trying to build a bot to automate some actions in a mobile game that Im running on my pc through Bluestacks.My program takes a screenshot of the window, looks for certain button templates in the …

how to store an image into redis using python / PIL

Im using python and the Image module(PIL) to process images.I want to store the raw bits stream of the image object to redis so that others can directly read the images from redis using nginx & htt…

Delete OCR word from Image (OpenCV,Python)

So, from what I can begin..I am working with OCR. The script works pretty well for what I need. It detects the words with an accuracy which for me is ok.This is the result: 100% accuracy with attached …

pandas.to_datetime inconsistent time string format

I am attempting to convert the index of a pandas.DataFrame from string format to a datetime index, using pandas.to_datetime().Import pandas:In [1]: import pandas as pdIn [2]: pd.__version__ Out[2]: 0.1…