Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: format multitline strings with variables

I'm writing a Python script at work that contains a part with a large multiline string that also needs to expand variables. I'm used to doing it the following way in Python 2.6 or Python 3:

message = """
          Hello, {foo}
          Sincerely, {bar}
          """
print (message.format(foo = "John", bar = "Doe"))

However, the server at work is running an old version of Python (2.3.4), which doesn't support string.format. What's a way to do this in old Python versions? Can you do it using the % operator? I tried this, but it didn't seem to work:

message = """
          Hello, %(foo)
          Sincerely, %(bar)
          """ % {'foo': 'John', 'bar': "Doe"}

I could just do it without using multiline strings, but the messages I need to format are quite large with a lot of variables. Is there an easy way to do that in Python 2.3.4? (Still a Python beginner, so sorry if this is a dumb question.)

like image 286
Nate Avatar asked Dec 02 '22 23:12

Nate


2 Answers

You want to say

message = """
          Hello, %(foo)s
          Sincerely, %(bar)s
          """ % {'foo': 'John', 'bar': "Doe"}

Note the s at the end, which makes the general format "%(keyname)s" % {"keyname": "value"}

like image 120
Eli Courtwright Avatar answered Dec 04 '22 11:12

Eli Courtwright


Try this

message = """
          Hello, %(foo)s
          Sincerely, %(bar)s
          """ % {'foo': "John", 'bar': "Doe"}
like image 22
MattH Avatar answered Dec 04 '22 13:12

MattH