Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python TypeError when using variable in re.sub

Tags:

python

regex

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?

like image 351
ReggieS2422 Avatar asked Nov 22 '25 19:11

ReggieS2422


1 Answers

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)
like image 69
mgilson Avatar answered Nov 24 '25 07:11

mgilson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!