3

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.)

4 Answers 4

12

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"}

Sign up to request clarification or add additional context in comments.

4 Comments

Gotcha, thanks to you and Matt. That's what I was missing, works great now.
How about concatenating variables?
@AllDani: I'm not sure what you're asking. If your question is, "How do I format a string which involves 2 variables interpolated right next to one another then the answers is to do something like 'Hello %(foo)s%(bar)s' % {'foo': 'x', 'bar': 'y'}. (Or you can use the new str.format approach, which was not an option for the OP since they're on an older version of Python.)
A multiline set of variables.
3

Try this

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

Comments

2

Dictionary based string formating

message = """
          Hello, %(foo)s
          Sincerely, %(bar)s
          """ % { "foo":"john","bar":"doe"}

Comments

0

You have a typo:

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

Replace the single quote with a double quote and it should run just fine.

1 Comment

Whoops, thanks. I typed it right on the computer, just made my post wrong. Let me edit that out.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.