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.)
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"}
Try this
message = """
Hello, %(foo)s
Sincerely, %(bar)s
""" % {'foo': "John", 'bar': "Doe"}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With