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?

1
  • This depends on your Python version. F-strings, as proposed by Aaron_ab, are available from 3.6 onward. Commented Jan 8, 2019 at 15:56

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

2 Comments

Notice the tecenique with the dictionary can raise exception when have no relevant keys in the dict to place..
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.
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

2 Comments

Good answer, but this assumes OP has python3.6
Good point. This will work only in 3.6 and above.. I like your answer as well with the dictionary

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.