Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoid duplicating arguments to str.format?

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?

like image 727
M.Ustun Avatar asked Oct 20 '25 07:10

M.Ustun


1 Answers

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
like image 195
cs95 Avatar answered Oct 22 '25 21:10

cs95



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!