I have a file name:
filename = 'Review Report - 2020-3.2021081716552'
Now I used 2 lines to just pick '2020-3', '2020-3' is dynamic ,can be other value:
report_name, ext = os.path.basename(filename).split(".")
a, b = report_name.split(" - ")
b will equal to '2020-3'
Can I just use 1 line code to get '2020-3' ?
CodePudding user response:
Use Maxsplit: One Liner:
date = filename.split(".")[0].split(" - ",maxsplit=1)[1]
Using one Liner is not recommended in Development of Projects, I recommend you to use the following:
filename = 'Review Report - 2020-3.2021081716552'
report_name, ext = filename.split(".")
a, b = report_name.split(" - ",maxsplit=1)
print(b)
OUTPUT:
2020-3
CodePudding user response:
The split()
function returns a list, so you can use the indices to get the respective string instead of declaring two variables to hold the values.
import os
filename = 'Review Report - 2020-3.2021081716552'
the_thing_you_want = os.path.basename(filename).split(".")[0].split(" - ")[1]
print(the_thing_you_want)
It will return 2020-3
.
If that helped, it'd be great if you could upvote and/or mark mine as the correct answer :)