Home > Programming, python, Tip, Uncategorized > Make good use of string formatting with python

Make good use of string formatting with python

Sometimes it’s better to separate program from content (MVC web programming is a good example). With python’s string formatting feature, this can be done quite easily. I am going to borrow a party emailing example from “Unix Shells by Example” and simplify it a bit. Let’s say I am going to hold a party and I am going to email my friends asking each of them to bring something for the party. I start by writing the following python script (main.py) and the email template (content)

main.py:

#!/usr/bin/env python
        
def main():
        friends=[
                { 'name':'Leah', 'stuff':'some cookies' },
                { 'name':'Michael', 'stuff':'a lot of beers' },
                { 'name':'Rachael', 'stuff':'a red wine' }
        ]
                
        with open('content') as f:
                content=f.read()

        for friend in friends:
                print(content % friend)
        

if __name__=='__main__':
        main()

content:

Dear %(name)s,
We are going to have a party this Friday night at my place, please make sure to bring %(stuff)s.

Sincerely Yours,
Party Animal

Save both files and at command prompt, run

python main.py

Advertisements
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: