I have this regex function to extract a specific word in a string
fileName = re.search(r'path1\w([A-Za-z\d]+)', self.fileList[0]).group(1)
path1 is an actual string
What if I would like to replace it by fileName variable where fileName = "path1"
I tried:
print re.search(r'\w([A-Za-z\d]+)' % fileName, self.fileList[0]).group(1)
I got this error:
TypeError: not all arguments converted during string formatting
Why did I get this error ? how to solve this problem
You need a %s in your regex :
print re.search(r'%s\w([A-Za-z\d]+)' % fileName, self.fileList[0]).group(1)
Or as a more pythoinc and flexible way you can use str.format function :
print re.search(r'{}\w([A-Za-z\d]+)'.format(fileName), self.fileList[0]).group(1)
Note that is second way if you have a list of file names you can loop over them and pass the file names to format.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With