Reputation: 57
I'm new to python and I keep getting an error doing the simpliest thing.
I'm trying to use a variable in a regular expression and replace that with an *
the following gets me the error "TypeError: not all arguments converted during string formatting" and I can't tell why. this should be so simple.
import re
file = "my123filename.zip"
pattern = "123"
re.sub(r'%s', "*", file) % pattern
Error: Traceback (most recent call last): File "", line 1, in ? TypeError: not all arguments converted during string formatting
Any tips?
Upvotes: 3
Views: 7216
Reputation: 310069
You're problem is on this line:
re.sub(r'%s', "*", file) % pattern
What you're doing is replacing every occurance of %s
with *
in the text from the string file
(in this case, I'd recommend renaming the variable filename
to avoid shadowing the builtin file
object and to make it more explicit what you're working with). Then you're trying to replace the %s
in the (already replaced) text with pattern
. However, file
doesn't have any format modifiers in it which leads to the TypeError
you see. It's basically the same as:
'this is a string' % ("foobar!")
which will give you the same error.
What you probably want is something more like:
re.sub(str(pattern),'*',file)
which is exactly equivalent to:
re.sub(r'%s' % pattern,'*',file)
Upvotes: 6
Reputation: 179552
Try re.sub(pattern, "*", file)
? Or maybe skip re
altogether and just do file.replace("123", "*")
.
Upvotes: 0