4

I'm currently using string formatting in my code however I find that I'm hard coding to display repeated variables. Is there a more efficient way to do this

print("Hello this is {} and {} and {} - Hello this is {} and {} and {} ".format(versionP, versionS, versionT, versionP, versionS, versionT))

The outcome is the one I want but I need to repeat this in several instances and can become tedious. Is there a way to only write the variable once?

cs95
  • 379,657
  • 97
  • 704
  • 746
M.Ustun
  • 289
  • 2
  • 6
  • 16

2 Answers2

8

You can specify positions, and str.format will know which arguments to use:

a, b, c = 1, 2, 3
string = "This is {0}, {1}, and {2}. Or, in reverse: {2}, {1}, {0}"
string.format(a, b, c)
# 'This is 1, 2, and 3. Or, in reverse: 3, 2, 1'

You may also pass keyword arguments, or unpack a dictionary:

a, b, c = 1, 2, 3
string = """This is {versionP}, {versionS}, and {versionT}. 
            Or, in reverse: {versionT}, {versionS}, {versionP}"""
# string.format(versionP=a, versionS=b, versionT=c)
string.format(**{'versionP': a, 'versionS': b, 'versionT': c})
# This is 1, 2, and 3. 
#       Or, in reverse: 3, 2, 1
cs95
  • 379,657
  • 97
  • 704
  • 746
  • Notice the tecenique with the dictionary can raise exception when have no relevant keys in the dict to place.. – Aaron_ab Jan 08 '19 at 16:01
  • 1
    Note to OP: I have converted my answer into runnable examples so you can see for yourself how this works. The process is identical for your use case. – cs95 Jan 08 '19 at 16:04
6

Python 3.6

I find it clean and simple:

print(f"Hello this is {versionP} and {versionS} and {versionT} - 
        Hello this is {versionP} and {versionS} and {versionT}")

You can even evaluate methods inside f-formatting or nested f-strings

cs95
  • 379,657
  • 97
  • 704
  • 746
Aaron_ab
  • 3,450
  • 3
  • 28
  • 42