What is the most pythonic way to build up large strings?

cstrutton11 at gmail.com cstrutton11 at gmail.com
Sat Feb 8 02:41:53 EST 2014


I am writing a couple of class methods to build up several lines of html. Some of the lines are conditional and most need variables inserted in them. Searching the web has given me a few ideas. Each has its pro's and cons.
The best I have come up with is:
def output_header_js(self, jquery=True, theme=None):
 if self.static_path is None :
 return None
 if jquery is True:
 output = '"<script type="text/javascript" '
 output += 'src="/%s/jquery/jqueryui.js"></script>'% static
 output += '"<script type="text/javascript" '
 output += 'src="/%s/jquery/jquery.js"></script>'% static
 if theme is not None:
 output += '<link href="/%s/jtable/themes/%s/jtable.css" '% static, theme
 output += 'rel="stylesheet" type="text/css" />'
 output += '"<script type="text/javascript" '
 output += 'src="/%s/jtable/jquery.jtable.js"></script>' % "static"
I realize that a lot of the above looks repetitive but it is designed to eliminate boilerplate HTML.
I have another method that will build some javascript that looks like this:
$('#StudentTableContainer').jtable({
 title: 'The Student List',
 paging: true, //Enable paging
 pageSize: 10, //Set page size (default: 10)
 sorting: true, //Enable sorting
 defaultSorting: 'Name ASC', //Set default sorting
 actions: {
 listAction: '/Demo/StudentList',
 deleteAction: '/Demo/DeleteStudent',
 updateAction: '/Demo/UpdateStudent',
 createAction: '/Demo/CreateStudent'
 },
 fields: {
 StudentId: {
 key: true,
 create: false,
 edit: false,
 list: false
 },
 Name: {
 title: 'Name',
 width: '23%'
 },
 EmailAddress: {
 title: 'Email address',
 list: false
 },
 ...
Almost every line in this code will require variable insertion or if statements.
Any thoughts on how to improve this? Thanks in advance. Chris


More information about the Python-list mailing list

AltStyle によって変換されたページ (->オリジナル) /