【发布时间】:2013-05-24 08:38:38
【问题描述】:
我希望能够在已经包含% 符号的字符串中使用占位符。例如,我希望能够通过我的 URL 已经包含 % 符号来迭代打开多个 URL,例如 url:
http://www.example.com/BLABLA%123BLABLApage=1
为此,我想用占位符 (%d) 替换数字 1,但代码似乎被占位符之前的 % 的存在弄糊涂了。
【问题讨论】:
标签: python placeholder
我希望能够在已经包含% 符号的字符串中使用占位符。例如,我希望能够通过我的 URL 已经包含 % 符号来迭代打开多个 URL,例如 url:
http://www.example.com/BLABLA%123BLABLApage=1
为此,我想用占位符 (%d) 替换数字 1,但代码似乎被占位符之前的 % 的存在弄糊涂了。
【问题讨论】:
标签: python placeholder
你可以通过加倍来逃避%:
>>> 'http://www.example.com/BLABLA%%123BLABLApage=%d' % (1,)
'http://www.example.com/BLABLA%123BLABLApage=1'
或者,改用str.format() 格式:
>>> 'http://www.example.com/BLABLA%123BLABLApage={:d}'.format(1)
'http://www.example.com/BLABLA%123BLABLApage=1'
【讨论】:
format 的使用,例如"http://www.example.com/BLABLA%123BLABLApage={page}".format(page=1)