Home > Software design >  Is there a way to do multiple different string replacements at once?
Is there a way to do multiple different string replacements at once?

Time:05-30

I am doing a university assignment and since we are excluded from using any web scrapping libraries, I am limited to regex, I have the current code written (excuse the poor formatting, I am still very new):

def print_ticket():
    if event.get() == 1:
        web_page = urlopen(url1)
        html_code = web_page.read().decode("UTF-8")
        web_page.close()
        event_title = findall('<h6.*>(. )</h6>', html_code)[0]
        event_image = findall('<img.* src="([^"] )".*>', html_code)[4]
        event_url = 'https://suncorpstadium.com.au/what-s-on.aspx'
        event_details = findall('<h7.*>(. )</h7>', html_code)[1]
        filename = event_title.replace(' ', '_')   '_Ticket.html'
        html_file = open(filename, 'w')
        html_file.write(ticket_template.replace('EVENT TITLE', event_title   ' Ticket'))
        html_file.write(ticket_template.replace('IMAGE', event_image))
        html_file.write(ticket_template.replace('DATE TIME', event_details))

My issue is, everytime I run that that event in my GUI, my web document prints 3 different sets of my template with the .write replaces occurring on one per section.

Is there a way to make multiple .replaces at once without it printing multiple copies of my template?

enter image description here

CodePudding user response:

The problem is that you are calling write 3 times and you need to call it just once. So what you could do:

        ticket_template = ticket_template.replace('EVENT TITLE', event_title   ' Ticket')
        ticket_template = ticket_template.replace('IMAGE', event_image)
        ticket_template = ticket_template.replace('DATE TIME', event_details)
        html_file.write(ticket_template)

in that way it will work, and you will only have the final output of the ticket_template. Also you can reduce this to a one-liner but it won't look legible

html_file.write(ticket_template.replace('EVENT TITLE', event_title   ' Ticket').replace('IMAGE', event_image).replace('DATE TIME', event_details))

CodePudding user response:

You can do it using an "f-string" or Formatted string literal which was introduced in Python 3.6. To control its evaluation, it must be specified as part of a lambda function as shown in the sample below. Note that the variable names used do not have to be ALL_CAPS as shown — I did it that way to make it easier to spot where they're being used.

ticket_template = lambda: f'''\
Congratulations! Your ticket to {EVENT_TITLE} has been booked!
{IMAGE}
{DATE} {TIME}
'''

filename = 'whatever.html'

with open(filename, 'w') as html_file:

    EVENT_TITLE = 'Some event title'
    IMAGE = 'Picture of event'
    DATE, TIME = '29/05', '4:00 PM'

    filled_in_ticket = ticket_template()
    html_file.write(filled_in_ticket)

print('fini')

  • Related