Python: formatting strings


/ Published in: Python
Save to your folder(s)

Python allows for strings to be formatted using a predefined format string with a list of variables.
The following is an example of using multiple format strings to display the same data:


Copy this code and paste it in your HTML
  1. >>>list = ["Brad", "Dayley", "Python Phrasebook",
  2. 2006]
  3.  
  4. >>>letter = """
  5. >>>Dear Mr. %s,\n
  6. >>>Thank you for your %s book submission.
  7. >>>You should be hearing from us in %d."""
  8.  
  9. >>>display = """
  10. >>>Title: %s
  11. >>>Author: %s, %s
  12. >>>Date: %d"""
  13.  
  14. >>>record = "%s|%s|%s|%08d"
  15.  
  16. >>>print letter % (list[1], list[2], list[3])
  17. Dear Mr. Dayley,
  18. Thank you for your Python Phrasebook book submission.
  19. You should be hearing from us in 2006.
  20.  
  21. >>>print display % (list[2], list[1], list[0],
  22. list[3])
  23. Title: Python Phrasebook
  24. Author: Dayley, Brad
  25. Date: 2006
  26.  
  27. >>>print record % (list[0], list[1], list[2],
  28. list[3])
  29. Brad|Dayley|Python Phrasebook|00002006

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.