0

I have a weird variable name for a dictionary that I have to use that looks like so:

val.display_counter1.rjj = {} 

This is illegal so I've decided to use this format:

val_display__counter1_rjj = {}

Later in the code I need to match up that dict variable name with the original name. So I'm trying to find a way to replace those single underscores with dots and the double underscores with a single underscore. I'm sure that there is a regex solution, but regex isn't my strong suit.

Is there a way to selectively replace like this?

Edit:

There is some confusion with my question so allow me to clarify. The original name:

val.display_counter1.rjj

This is NOT a variable in itself but merely an item name from the 3D software package Modo. There are many items that share this format. What I am trying to do is create a class of dicts that will store information about these items. I want to name the dicts for the items and be able to match them in program.

For me to make this match I need to revert my dict name back to it's original so I can make the match:

val_display__counter1_rjj --> val.display_counter1.rjj

All I need to know is how to make the Regex match ONLY the single underscore and discard the matches that are surrounded by other underscores.

Also, not sure why this is marked as duplicate. But my question doesn't involve dynamic variables.

Berkyjay
  • 158
  • 1
  • 1
  • 10
  • 1
    Are you planning to do this with Python `re`? Here is [an example](http://stackoverflow.com/questions/31242920/replace-a-substring-selectively-inside-a-string) of what you might want to try but the pattern and replacements will be different here. – Wiktor Stribiżew Oct 06 '16 at 21:21
  • 2
    What happens when the original data is `val._display` vs. `val_.display`, both of which are perfectly legal names? The transformed version is `val___display` in either case, so you've lost information. – ShadowRanger Oct 06 '16 at 21:22
  • 6
    It sounds like instead of making this a variable and messing with variable names, you could just store this dict in another dict under the key `'val.display_counter1.rjj'`. – user2357112 Oct 06 '16 at 21:24

1 Answers1

-1

Well, I am new to Python. But hope this works!!!

    import re;
    val_display__counter1_rij= {};
    l = ['val_display__counter1_rij', 'val_display___counter1_rij','val.display__counter1_rij']  # list of variables to match
    for x in l:
       if "." not in x:
          article = re.sub(r'(?is)_', '.', x)
          if ".." in article:
              article= article.replace("..","__");

          if (article == 'val.display__counter1.rij'):
              print(article)