【问题标题】:Multiline string substitution in PythonPython 中的多行字符串替换
【发布时间】:2023-02-23 09:32:41
【问题描述】:

我正在尝试这个:

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)

这是我的工作,但我正在寻找类似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"
    }
  ]
}"""

我收到以下错误:

SyntaxError: f-string: expressions nested too deeply

除了使用 .replace() 之外还有其他方法吗?

【问题讨论】:

    标签: python


    【解决方案1】:

    当您使用 f 字符串时,所有这些大括号都会开始一个表达式,但在您的情况下,它们只是文字大括号。你必须为此使用双括号。

    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"
        }}
      ]
    }}"""
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-06-13
      • 1970-01-01
      • 1970-01-01
      • 2022-01-03
      • 2019-10-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多