使用.format()时,Python错误地读取字典的字符串

我正在Python 3.6.6中创建字典的字符串(稍后添加到.txt文件)。

当我对字典的字符串进行硬编码时,没有任何问题:

my_string = '{"source": "s3://some_s3_bucket/random_filename.csv"} \n'
print(my_string)

输出

{“来源”:“ s3://some_s3_bucket/random_filename.csv”}

但是,当我尝试用硬编码的文件路径替换变量时,Python似乎开始假设“源”是我要替换的变量:

bucket = "some_s3_bucket"
filename = "random_filename.csv"
my_new_string = '{"source": "s3://{0}/{1}"} \n'.format(bucket, filename)
print(my_new_string)

输出

KeyError追踪(最近一次通话)    在模块中   -> 1 my_new_string ='{“源”:“ s3:// {0} / {1}”} \ n'.format(存储桶,文件名)   2打印(my_new_string)      KeyError:““源”'

我应该如何格式化此字符串以使Python正确读取我的存储桶和文件名变量?

评论
  • Susie
    Susie 回复

    format triggers replacements on curly braces. You have a curly brace at the start of the string.

    要输出大括号,请将其加倍:

    my_new_string = '{{"source": "s3://{0}/{1}"}} \n'.format(bucket, filename)
    

    but Talon's comment is right, using json module would be better than making JSON by hand, since the variables' values might need escaping, in the general case. Since you will then have no braces you'd need to output, your format problem disappears:

    import json
    my_new_string = json.dumps({"source": "s3://{0}/{1}".format(bucket, filename) })
    
  • UFO
    UFO 回复

    You are using string format so you have to use double {{ data }}

    In [1]: bucket = "some_s3_bucket" 
       ...: filename = "random_filename.csv" 
       ...: my_new_string = '{{"source": "s3://{0}/{1}"}} \n'.format(bucket, filename) 
       ...: print(my_new_string)                                                                                                                          
    {"source": "s3://some_s3_bucket/random_filename.csv"\}
    

    Check this for more information How can I print literal curly-brace characters in python string and also use .format on it?

  • 贪婪
    贪婪 回复

    str.format() uses {} characters as placeholders for parameters to be formatted. You used { at the beginning of your format string, and that causes the problem. What you want to do is to use double braces {{ & }} where they need to be taken as literal braces rather than substituted:

    my_new_string = '{{"source": "s3://{0}/{1}"}} \n'.format(bucket, filename)
    

    此外,这是生成JSON数据的一种糟糕方法(请参阅Talon的评论)。