0

I have the following list Novar:

["'population_3000|road_class_3_3000'", "'population_3000|road_class_3_3000|trafBuf25'", "'population_3000|road_class_3_3000|trafBuf25|population_1000'"]

How can I append a character (e.g. $) to a specific part of the items in the list, for instance to road_class_3_3000, so that the upgraded list becomes:

["'population_3000|road_class_3_3000$'", "'population_3000|road_class_3_3000$|trafBuf25'", "'population_3000|road_class_3_3000$|trafBuf25|population_1000'"]

Most similar questions on Stack Overflow seem to focus on manipulating the item itself, rather than a part of the item, e.g. here and here.

Therefore, applying the following code:

    if (item == "road_class_3_3000"):
        item.append("$")

Would be of no use since road_class_3_3000 is part of the items "'population_3000|road_class_3_3000'", "'population_3000|road_class_3_3000|trafBuf25'" and "'population_3000|road_class_3_3000|trafBuf25|population_1000'"

1 Answers1

2

You might harness re module (part of standard library) for this task following way

import re
novar = ["'population_3000|road_class_3_3000'", "'population_3000|road_class_3_3000|trafBuf25'", "'population_3000|road_class_3_3000|trafBuf25|population_1000'"]
novar2 = [re.sub(r'(?<=road_class_3_3000)', '$', i) for i in novar]
print(novar2)

output

["'population_3000|road_class_3_3000$'", "'population_3000|road_class_3_3000$|trafBuf25'", "'population_3000|road_class_3_3000$|trafBuf25|population_1000'"]

Feature I used is called positive lookbehind, it is kind of zero-length assertion. I look for place after road_class_3_3000 of zer-length, which I then replace using $ character.

Daweo
  • 31,313
  • 3
  • 12
  • 25
  • How would this apply if there is an additional part to the item that contains ```road_class_3_30000``` whereby you do not want the operation to affect that part? Applying ```[re.sub(r'(?<=road_class_3_3000)', '$', i) for i in novar]``` would, in this case, also result in ```road_class_3_3000$0``` (while you want ```road_class_3_30000``` intact). – Foeke Boersma May 26 '22 at 08:22
  • @FoekeBoersma to prevent such behavior replace `r'(?<=road_class_3_3000)'` using `r'(?<=road_class_3_3000)\b'` where `\b` is another zero-length assertion which is word boundary, see [`re` module docs](https://docs.python.org/3/library/re.html) for further discussion of that feature – Daweo May 26 '22 at 08:25