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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With