Skip to content
Advertisement

Replacing a variable in a list with the result of a regex search in a Python function

I have three lists lst_a to lst_c. I would like to write a function that takes each item from the lists, performs a regex search according to lst_b with search group position according to lst_c and replaces the variables in lst_a with the search results.

This is my code:

JavaScript

Searching and finding works, but I cannot get the function to save its results into the variables in lst_a. This is what I get instead:

JavaScript

The expected output for the used positional parameter in my example should be:

JavaScript

Advertisement

Answer

First of all, the expected result is not consistent. It would mean that the third regular expression “(foo)(baz)(bar)” would find a match in “foobarbaz”, which is not true. So also the third result should be “not found”.

Then some remarks on your attempt:

  • As arguments become local variables, you cannot expect the function to change the global list_a by just assigning to the local variable variables. list_a will not change by running this function.

  • To overcome the first issue, it would be more fitting to have the function return the list with the three results, and to not pass an argument for that.

  • Since you want to produce a list, you should not assign a result to variables, but append the results to it, and so build the list you want to return

  • Avoid global statements. They are not needed here.

  • Avoid a hard-coded value in your function like “foobarbaz”. Instead pass it as argument to the function, so it becomes more flexible.

  • Not an issue, but although your problem statement speaks of a list_c, your code only ever uses one value from that list. So then it doesn’t need to be a list. But I’ll leave that part untouched.

  • I would avoid calling a variable variables, which suggests that this variable contains variables… which makes little sense. Let’s call it results.

Here is a correction:

JavaScript
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement