Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Extract parameters from variable length python f-string

Using Python 3.6

I have an f-string 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)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading