python - 是否可以防止 python 中的百分比字符串替换

标签 python string substitution

>>> 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/

相关文章:

regex - 使用正则表达式的 Bash 变量替换无法按预期工作

python - 我想抓取多个页面,但我得到了最后一个 url 的结果。为什么?

python - 如何使用 LXML 或 BeautifulSoup 删除 CDATA 标签但保留 Python 中的实际数据

C#:是否与 C# 的 php ctype_digit 函数类似?

java - 在java文件中使用超链接

string - 批处理 : String substitution sub

python - 在Python中读取单个字符(而不是字节)而不等待行尾或EOF

python - 如何在 Pandas 中交换一组列标题及其值

java - 字符串输出 : Class@#

sed - 如何使用sed用文件内容替换两个模式之间的多行?