【问题标题】:python triple quote string adding multiple variablespython三引号字符串添加多个变量
【发布时间】:2016-08-07 18:13:36
【问题描述】:

我正在使用 python 2.7。我有一个三引号字符串,我想在其中添加 4 个变量。然后,该字符串将在我们的 REST API 将处理的发布请求中使用。下面是字符串,它被缩短了 500 多行:

curDate = str(datetime.datetime.now().year)+"/"+str(datetime.datetime.now().month)+"/"+str(datetime.datetime.now().day)\
          +" "+str(datetime.datetime.now().hour)+":"+str(datetime.datetime.now().minute)+":"\
          +str(datetime.datetime.now().second)

...

payload = '''
   ...
"CaptureTime": %(captureTime),
   ...
"dataTime1": %(dataTime1)
   ...
"dataTime2": %(dataTime2)
   ...
"dataTime3": %(dataTime3)
   ...
"dataTime4": %(dataTime4)
   ...
''' % dict(captureTime=curDate, dataTime1=curDate, dataTime2=curDate, dataTime3=curDate, dataTime4=curDate)

这是我收到的错误:

Traceback (most recent call last):
  File "/xxx/xxxx/xxxxxx/Rest/Post.py", line 6130, in <module>
    ''' % {'captureTime':curDate, 'dataTime1':curDate, 'dataTime2':curDate, 'dataTime3':curDate, 'dataTime4':curDate}
ValueError: unsupported format character ',' (0x2c) at index 204

感谢您的所有帮助!

【问题讨论】:

  • 您无缘无故地多次评估datetime.datetime.now()。它返回一个namedtuple。只需评估一次并为其命名并使其高效。

标签: python string


【解决方案1】:

问题是你用的:

%(captureTime),

而不是限定类型(我假设您正在尝试限定为字符串):

%(captureTime)s,

所以逗号不被识别为 % 的类型限定符。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-12
    • 2018-01-12
    • 1970-01-01
    • 1970-01-01
    • 2011-04-23
    相关资源
    最近更新 更多