Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

multiline string substitution in python

I am trying this out.

account = "11111111111"
tenant_name= "Demo"
project_name= "demo"

sns_access_policy = """{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "0",
      "Effect": "Allow",
      "Principal": {
        "Service": "codestar-notifications.amazonaws.com"
      },
      "Action": "sns:Publish",
      "Resource": "arn:aws:sns:eu-west-1:{account_id}:{tenant_name}-{project_name}-pipeline-monitoring"
    }
  ]
}"""

sns_access_policy = sns_access_policy.replace("{account_id}",account).replace("{tenant_name}",tenant_name).replace("{project_name}",project_name)

This is doing my work, but I am looking something like f{string_substitution}.

sns_access_policy = f"""{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "0",
      "Effect": "Allow",
      "Principal": {
        "Service": "codestar-notifications.amazonaws.com"
      },
      "Action": "sns:Publish",
      "Resource": "arn:aws:sns:eu-west-1:{account}:{tenant_name}-{project_name}-pipeline-monitoring"
    }
  ]
}"""

I am getting an error

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

SyntaxError: f-string: expressions nested too deeply

is there any other way than using replace() for this?

>Solution :

When you use an f-string all those braces start an expression, but in your case they are just literal braces. You have to use double braces for that.

sns_access_policy = f"""{{
  "Version": "2012-10-17",
  "Statement": [
    {{
      "Sid": "0",
      "Effect": "Allow",
      "Principal": {{
        "Service": "codestar-notifications.amazonaws.com"
      }},
      "Action": "sns:Publish",
      "Resource": "arn:aws:sns:eu-west-1:{account}:{tenant_name}-{project_name}-pipeline-monitoring"
    }}
  ]
}}"""
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading