包含%符号的字符串中的Python占位符 [英] Python placeholders in strings containing the % symbol
本文介绍了包含%符号的字符串中的Python占位符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我希望能够在已经包含%
符号的字符串中使用占位符.例如,我希望能够迭代打开多个URL,因为我的URL已经包含%
符号,例如url:
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
为此,我想用一个占位符(%d
)替换数字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.
推荐答案
您可以通过将%
加倍来对其进行转义:
You can escape %
by doubling it:
>>> 'http://www.example.com/BLABLA%%123BLABLApage=%d' % (1,)
'http://www.example.com/BLABLA%123BLABLApage=1'
或者,使用 str.format()
格式设置:
Alternatively, use str.format()
formatting instead:
>>> 'http://www.example.com/BLABLA%123BLABLApage={:d}'.format(1)
'http://www.example.com/BLABLA%123BLABLApage=1'
这篇关于包含%符号的字符串中的Python占位符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文