Skip to content
Advertisement

Extract parameters from variable length python f-string

Using Python 3.6

I have an f-string in main that looks like

title =f'Backup errors in {folder} on {host} at {datetime.datetime.today()}'

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:

extracted_folder = title.split()[17:30]

but folder and host are both going to be variable length.

Advertisement

Answer

you can do a combination of split and slice like this :

title = 'Backup errors in folder 1234 on host1234 at today1234'
folder = title[17:].split(' on ')[-2]
host = title[17:].split(' on ')[-1].split(' at ')[0]
print(folder)
print(host)

output :

folder 1234
host1234

I also work with spaces and with ” on ” in the folder name if you do an other trick :

title = 'Backup errors in folder on 1234 on host1234 at today1234'
folder = " on ".join(title[17:].split(' on ')[:-1])
host = title[17:].split(' on ')[-1].split(' at ')[0]
print(folder)
print(host)

output :

folder on 1234
host1234
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement