Python placeholders in strings containing the % symbol

大兔子大兔子 提交于 2019-12-17 23:29:10

问题


I want to be able to use a placeholder in a string that already contains a % symbol. For instance, I would like to be able to iterate to open multiple URLs by my URL already contains a % symbol, example url:

http://www.example.com/BLABLA%123BLABLApage=1

To do so, I want to replace the number 1 by a placeholder (%d), but the code seems to be confused by the presence of the % that comes before the placeholder.


回答1:


You can escape % by doubling it:

>>> 'http://www.example.com/BLABLA%%123BLABLApage=%d' % (1,)
'http://www.example.com/BLABLA%123BLABLApage=1'

Alternatively, use str.format() formatting instead:

>>> 'http://www.example.com/BLABLA%123BLABLApage={:d}'.format(1)
'http://www.example.com/BLABLA%123BLABLApage=1'


来源:https://stackoverflow.com/questions/16807904/python-placeholders-in-strings-containing-the-symbol

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!