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.
CodePudding user response:
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
CodePudding user response:
You can use the re module. E.g.:
import re
# regular expression version of text for matching
retext = r'Backup errors in (?P<folder>\S ) on (?P<hostname>\S ) at'
# string containing information
text = 'Backup errors in myfolder on myhost at 17:23:45'
# get dictionary containing the parts of your text
info = re.match(retext, text).groupdict()
print(info)
{'folder': 'myfolder', 'hostname': 'myhost'}
CodePudding user response:
If folder and host are sigle words (no spaces):
>>> title = "Backup errors in /var/mail/filename.log on myserver.domain at ..."
>>> words = title.split(' ')
>>> words[3]
'/var/mail/filename.log'
>>> words[5]
'myserver.domain'
