为了账号安全,请及时绑定邮箱和手机立即绑定

如何有选择地在Python字符串中转义百分比(%)?

如何有选择地在Python字符串中转义百分比(%)?

弑天下 2019-11-17 12:12:08
如何有选择地在Python字符串中转义百分比(%)?我有以下代码test = "have it break."selectiveEscape = "Print percent % in sentence and not %s" % testprint(selectiveEscape)我想获得输出:Print percent % in sentence and not have it break.实际发生了什么:    selectiveEscape = "Use percent % in sentence and not %s" % testTypeError: %d format: a number is required, not str
查看完整描述

3 回答

?
慕的地8271018

TA贡献1796条经验 获得超4个赞

>>> test = "have it break."

>>> selectiveEscape = "Print percent %% in sentence and not %s" % test

>>> print selectiveEscape

Print percent % in sentence and not have it break.


查看完整回答
反对 回复 2019-11-18
?
幕布斯7119047

TA贡献1794条经验 获得超8个赞

或者,从Python 2.6开始,您可以使用新的字符串格式(在PEP 3101中描述):

'Print percent % in sentence and not {0}'.format(test)

当你的琴弦变得更复杂时,这尤其方便。


查看完整回答
反对 回复 2019-11-18
?
神不在的星期二

TA贡献1963条经验 获得超6个赞

您不能有选择地逃避%,因为%总是具有特殊含义,具体取决于以下字符。

在Python 的文档中,在该部分的第二个表的bottem中,它指出:

'%'        No argument is converted, results in a '%' character in the result.

因此你应该使用:

selectiveEscape = "Print percent %% in sentence and not %s" % (test, )

(请注意将元组的expicit更改为参数%

如果不知道上述内容,我会做到:

selectiveEscape = "Print percent %s in sentence and not %s" % ('%', test)

凭借你显然已经拥有的知识。



查看完整回答
反对 回复 2019-11-18
  • 3 回答
  • 0 关注
  • 297 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信