简体   繁体   中英

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. 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:

[['2020', '11', '10'], ['2020', '12', '30'], ['2021', '1', '8']]
2020 11 10
2020 12 30
2021 1 8

You can use the split 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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM