Ryan Erwin
Ryan Erwin

Reputation: 817

re.sub - File path

I have a file name test.CSV and I want to replace with .xlsx. I want the use the re module to use the case insensitive feature. I just can't seem to figure this out:

test = re.compile('test.CSV', re.IGNORECASE)
test.sub('.xlsx', '.csv')
'.csv'

What am I missing? Seems like such a simple problem.

Upvotes: 0

Views: 1208

Answers (2)

wim
wim

Reputation: 363183

Fixing the regex:

>>> pattern = re.compile(r'\.CSV', re.IGNORECASE)
>>> pattern.sub(repl='.xlsx', string='test.CSV')
'test.xlsx'
>>> pattern.sub(repl='.xlsx', string='test.csv')
'test.xlsx'

Not using regex in the first place:

base, ext = os.path.splitext(fname)
if ext.lower() == '.csv':
    fname = base + '.xlsx'

Upvotes: 2

cs95
cs95

Reputation: 402872

If you're compiling a pattern, the first argument to re.compile has to be the pattern to replace. In your case, it should've been \.csv. However, for this specific case, I don't see any benefit in pre-compiling unless you use the same pattern multiple times.

So, using the top-level re.sub function should be sufficient:

>>> re.sub(r'\.csv', r'\.xlsx', 'test.CSV', flags=re.I)
'test\\.xlsx'

If not, compile and use the pattern like this:

>>> p = re.compile(r'\.csv', flags=re.I)
>>> p.sub(r'\.xslx', 'test.CSV')
'test\\.xslx'

Upvotes: 2

Related Questions