Using Python 3.6
I have an f-string in main
that looks like
JavaScript
x
2
1
title =f'Backup errors in {folder} on {host} at {datetime.datetime.today()}'
2
used in the following function call send_mail(title, message, to, from)
I am not allowed to change the function call.
The question is, inside send_email
can I extract the folder
, and host
variables from the f-string?
I would normally try something like:
JavaScript
1
2
1
extracted_folder = title.split()[17:30]
2
but folder
and host
are both going to be variable length.
Advertisement
Answer
you can do a combination of split and slice like this :
JavaScript
1
6
1
title = 'Backup errors in folder 1234 on host1234 at today1234'
2
folder = title[17:].split(' on ')[-2]
3
host = title[17:].split(' on ')[-1].split(' at ')[0]
4
print(folder)
5
print(host)
6
output :
JavaScript
1
3
1
folder 1234
2
host1234
3
I also work with spaces and with ” on ” in the folder name if you do an other trick :
JavaScript
1
6
1
title = 'Backup errors in folder on 1234 on host1234 at today1234'
2
folder = " on ".join(title[17:].split(' on ')[:-1])
3
host = title[17:].split(' on ')[-1].split(' at ')[0]
4
print(folder)
5
print(host)
6
output :
JavaScript
1
3
1
folder on 1234
2
host1234
3