Python: formatting multi-line strings with variables

I am writing a Python script at work that contains a part with a large multi-line string, which should also expand the variables. I used to do it like this in Python 2.6 or Python 3:

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

However, the old version of Python (2.3.4) runs on the production server, which does not support string.format. What is the way to do this in older versions of Python? Can you do this with 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 this without using multi-line strings, but the messages I need to format are quite large with lots of variables. Is there an easy way to do this in Python 2.3.4? (Still new to Python, sorry if this is a stupid question.)

+4
source share
4 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"}

+13
source

try it

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

Dictionary Based String Formation

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

You have a typo:

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

Replace the single quote with a double quote, and it should work fine.

0
source

Source: https://habr.com/ru/post/1403947/


All Articles