我想要提取由常量前缀和'.csv'分隔的文件名的最后一部分
文件名称可能如下所示:
constant_prefix_ 我的文件名 .csv
或
constant_prefix_的 mYfILEname的名称的.csv
我想将以粗体标记的值提取到变量中。
请告知。
答案 0 :(得分:4)
脚本:
import re
name1 = 'constant_prefix_my file name.csv'
name2 = 'constant_prefix_myfilename.csv'
def get_name(string):
return re.findall(r'constant_prefix_(my.*)\.csv', string)[0]
演示:
print get_name(name1)
print get_name(name2)
输出:
my file name
myfilename
或者你可以这样做:
names = [get_name(n) for n in [name1, name2]]
print names
输出:
['my file name', 'myfilename']
答案 1 :(得分:1)
使用str.split
和os.path.splitext
:
>>> import os
>>> prefix = 'constant_prefix'
# if your prefix includes the trailing `_` then don't use `_` in `str.split`
# i.e just use this : `strs.split(prefix)[-1]`
>>> name, ext = os.path.splitext(strs.split(prefix + '_')[-1])
>>> name
'myfilename'
>>> strs = "constant_prefix_my file name.csv"
>>> name, ext = os.path.splitext(strs.split(prefix + '_')[-1])
>>> name
'my file name'
答案 2 :(得分:0)
name1 = 'constant_prefix_my file name.csv'
name2 = 'constant_prefix_myfilename.csv'
constant_prefix = 'constant_prefix_'
name1 = name1[len(constant_prefix):-4] # 'my file name'
name2 = name2[len(constant_prefix):-4] # 'myfilename'