>>> 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!
Is there anyway to disable % symbol (operator.mod) from doing wacky string substitution stuff? I always use str.format if I need anything like that, and would generally rather this string substitution feature didn’t exist at all, giving a TypeError instead.
You can’t disable it with a switch, no. The
str()type implements a__mod__method to handle the formatting, it’s not that Python special-cased the expression just for strings.As such, to prevent this you either need to cast the
nargument to something that is not a string (by converting it toint()for example), or subclassstr()to override the__mod__method:You can assign this to
__builtins__.str, but this does not mean that all string literals will then use your subclass. You’d have to explicitly cast yourstr()values tonoformattingstr()instances instead.