How to indent a yaml file using regular expression?

Asked

Viewed 178 times

1

PROD ="IND"
LOCATION ="NY"
LOLO ="abc"
yaml_content = """
    MAIN :
      PROD : {}
      LOCATION : {}
    EXTRA :
      LOLO : {}
    """.format(PROD, LOCATION, LOLO)
yaml_content = re.sub("\n\s", "\n", yaml_content.strip())

print yaml_content

I have as output in print:

MAIN :
         PROD : IND
         LOCATION : NY
       EXTRA :
         LOLO : abc

There’s space I don’t want! The right way should be:

MAIN :
  PROD : IND
  LOCATION : NY
EXTRA :
  LOLO : abc

Someone knows how to rephrase the re.(...)

1 answer

1

Notice that the spaces are just inside your string:

yaml_content = """
    MAIN :
      PROD : {}
      LOCATION : {}
    EXTRA :
      LOLO : {}
    """.format(PROD, LOCATION, LOLO)

And the easiest way to solve this would be to produce something like:

yaml_content = (
    "MAIN:\n"+
        "\tPROD: {}\n" +
        "\tLOCATION: {}\n" +
    "EXTRA:\n" +
        "\tLOLO: {}\n").format(PROD, LOCATION, LOLO)

No need to use regex for such.

Of course, if what you want is to create a YAML file from data that is already stored in variables I recommend you to use the module Pyyaml because it will be enough to put the data inside a dictionary and the language will do the rest for you.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.