Python多行字符串替换:f-string嵌套报错后的替代方案咨询
你遇到的f-string报错是因为JSON里的大括号和f-string语法冲突了——f-string会把JSON结构里的{当成变量占位符解析,导致嵌套层级超标。除了.replace(),还有这几种靠谱的多行字符串变量替换方法:
方法1:转义f-string中的JSON大括号
把JSON里的每个{改成{{,}}改成}},让f-string只解析你真正需要替换的{account}这类变量占位符,不会误处理JSON结构的大括号:
account = "11111111111" tenant_name= "Demo" project_name= "demo" 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" }} ] }}"""
优缺点:保留f-string的直观性,但模板复杂时手动转义容易漏改。
方法2:使用str.format()方法
直接复用你原来的模板字符串,调用format()传入变量即可,不需要处理转义,比多次.replace()更简洁:
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" } ] }""".format(account_id=account, tenant_name=tenant_name, project_name=project_name)
优缺点:模板无需修改,代码整洁;如果占位符和变量名不一致,需要手动映射参数。
方法3:使用string.Template类
适合需要安全替换的场景(比如变量来自用户输入,避免格式字符串注入),用$作为占位符前缀:
from string import Template account = "11111111111" tenant_name= "Demo" project_name= "demo" template = Template("""{ "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 = template.substitute(account_id=account, tenant_name=tenant_name, project_name=project_name)
优缺点:安全性高,不会解析模板中的特殊字符;但需要修改占位符格式为$前缀。
内容的提问来源于stack exchange,提问作者Sumanth Shetty
相关产品推荐
相关产品推荐

