Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python regex: Turn "ThisFileName.txt" into "This File Name.txt"

Tags:

python

regex

I'm trying to add a space before every capital letter, except the first one.

Here's what I have so far, and the output I'm getting:

>>> tex = "ThisFileName.txt"
>>> re.sub('[A-Z].', ' ', tex)
' his ile ame.txt'

I want: 'This File Name.txt'

(It'd be nice if I could also get rid of .txt, but I can do that in a separate operation.)

like image 839
Jim Avatar asked Feb 02 '26 23:02

Jim


1 Answers

Key concept here is backreferences in regular expressions:

import re
text = "ThisFileName.txt"
print re.sub('([a-z])([A-Z])', r'\1 \2', text)
# Prints: "This File Name.txt"

For pulling off the '.txt' in a reliable way, I recommend os.path.splitext()

import os
filename = "ThisFileName.txt"
print os.path.splitext(filename)
# Prints: ('ThisFileName', '.txt')
like image 198
Kenan Banks Avatar answered Feb 05 '26 11:02

Kenan Banks



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!