I have an apk file say MyApp.apk. I was trying to strip the .apk extension using the strip function in python. But the problem is, If my applications name is WhatsApp.apk then the function strips the letters pp also and outputs WhatsA. What Regex should I use to strip exactly the .apk away?
Regex to select a file extension
4.3k views Asked by Anonymous Platypus At
6
There are 6 answers
0
On
For filenames i suggest using os.path.splitext
filename = "test.txt"
os.path.splitext(filename)
# ('test', '.txt')
If you are using filename.split() as other answers suggest you may get in trouble :
filename = "this.is.a.file.txt"
filename.split(".")
#['this', 'is', 'a', 'file', 'txt']
os.path.splitext(filename)
#('this.is.a.file', '.txt')
0
On
You can also accomplish this if you are certain that all the files end with .apk without using the string.replace function as
>>> str.replace('.apk','')
'MyApp'
A solution using re.sub would be like
>>> import re
>>> str="MyApp.apk"
>>> re.sub('r[\.[^.]+$','',str)
'MyApp.apk'
\.[^.]+matches a.followed by anything other than.till end of string
Why use regex? If you only want the filename then this code will do
output: