[英]how to substring string in python?
I have filenames like below:我有如下文件名:
PRJ25 Sample1 Siver_Output_Log_2020_11_10_13.csv
PRJ25 Sample1 Siver_Output_Log_2020_12_30_4_1.csv
PRJ25 Sample1 Siver_Output_Log_2021_1_8_4.csv
I want output to year, month, day
from these filenames.我希望这些文件名中的 output 为
year, month, day
。 I tried below code but filename is not consistent so i am unable to get these values, expected result:我尝试了下面的代码,但文件名不一致,所以我无法获得这些值,预期结果:
year : 2020 or 2021
month: 11 or 12 or 1
day: 10 or 30 or 8
My code:我的代码:
year = file_name[len(file_name) - 14:len(file_name) - 10]
month = file_name[len(file_name) - 9:len(file_name) - 8]
day = file_name[len(file_name) - 7:len(file_name) - 6]
Try this:尝试这个:
files = [
"PRJ25 Sample1 Siver_Output_Log_2020_11_10_13.csv",
"PRJ25 Sample1 Siver_Output_Log_2020_12_30_4_1.csv",
"PRJ25 Sample1 Siver_Output_Log_2021_1_8_4.csv",
]
results = [f.split("Log_")[-1].rsplit("_")[:3] for f in files]
print(results)
for result in results:
year, month, day = result
print(year, month, day)
# do your stuff here
Output: Output:
[['2020', '11', '10'], ['2020', '12', '30'], ['2021', '1', '8']]
2020 11 10
2020 12 30
2021 1 8
You can use the split function:您可以使用拆分 function:
year = file_name.split('_')[3]
Split transforms your string in a list of strings separated by the character you specified.拆分将您的字符串转换为由您指定的字符分隔的字符串列表。 For year I retrieve the 4th one.
一年来,我检索了第四个。
You could try this:你可以试试这个:
year, month, day, last_num = filename.split("_")[-4:]
last_num = last_num.split(".")[0]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.