What is the most pythonic way to build up large strings?
Rustom Mody
rustompmody at gmail.com
Sat Feb 8 07:33:10 EST 2014
On Saturday, February 8, 2014 4:58:03 PM UTC+5:30, Asaf Las wrote:
> Check this approach if it suits you:
> str_t= '<script type="text/javascript' \
> '<src="/{0}/jquery/jqueryui.js"></script>' \
> '<script type="text/javascript'\
> 'src="/{1}/jquery/jquery.js"></script>'.format('bella', 'donna')
> print(str_t)
Many people prefer this
>>> str_t= ( '<script type="text/javascript'
... '<src="/{0}/jquery/jqueryui.js"></script>'
... '<script type="text/javascript'
... 'src="/{1}/jquery/jquery.js"></script>'
... )
>>> str_t
'<script type="text/javascript<src="/{0}/jquery/jqueryui.js"></script><script type="text/javascriptsrc="/{1}/jquery/jquery.js"></script>'
Which is to say use the fact that adjacent string constants get automatically
concatenated. You avoid the ugly \ at EOL though you then need an enclosing paren.
However this is still C programmer style
Triple quotes are better
And templating engine is still better
And for more heavy duty use of format, it may be better to use
named-formats + a dict
>>> dc={'pth':'bella', 'file':'donna'}
>>> formatstr='<script type="text/javascript<src="/%(pth)s/jquery/jqueryui.js"></script><script type="text/javascriptsrc="/%(file)s/jquery/jquery.js"></script>'
>>> formatstr % dc
'<script type="text/javascript<src="/bella/jquery/jqueryui.js"></script><script type="text/javascriptsrc="/donna/jquery/jquery.js"></script>'
More information about the Python-list
mailing list