>>> def mod2(n):
... print 'the remainder is', n % 2
...
>>> mod2(5)
the remainder is 1
>>> mod2(2)
the remainder is 0
>>> mod2('%d')
the remainder is 2
>>> mod2('%d\rHELLO. I AM A POTATO!')
HELLO. I AM A POTATO!
有没有办法禁止 %
符号 (operator.mod
) 执行古怪的字符串替换操作?如果我需要类似的东西,我总是使用 str.format
,并且通常宁愿这个字符串替换功能根本不存在,而是给出一个 TypeError
。
最佳答案
你不能用开关禁用它,不。 str()
类型实现了一个 __mod__
method处理格式化,并不是 Python 将表达式特例化为字符串。
因此,为了防止这种情况,您要么需要将 n
参数转换为不是字符串的内容(通过将其转换为 int()
例如),或者子类 str()
来覆盖 __mod__
方法:
>>> class noformattingstr(str):
... def __mod__(self, other):
... raise TypeError('String formatting using "%" has been deprecated')
...
>>> noformattingstr('hello world: %d') % 10
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 3, in __mod__
TypeError: String formatting using "%" has been deprecated
您可以将其分配给 __builtins__.str
,但这不意味着所有字符串文字都将使用您的子类。您必须将 str()
值显式转换为 noformattingstr()
实例。
关于python - 是否可以防止 python 中的百分比字符串替换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13819497/