I'm trying to maintain/update/rewrite/fix a bit of Python that looks a bit like this:
variable = """My name is %s and it has been %s since I was born. My parents decided to call me %s because they thought %s was a nice name. %s is the same as %s.""" % (name, name, name, name, name, name)
There are little snippets that look like this all over the script, and I was wondering whether there's a simpler (more Pythonic?) way to write this code. I've found one instance of this that replaces the same variable about 30 times, and it just feels ugly.
Is the only way around the (in my opinion) ugliness to split it up into lots of little bits?
variable = """My name is %s and it has been %s since I was born.""" % (name, name) variable += """My parents decided to call me %s because they thought %s was a nice name.""" % (name, name) variable += """%s is the same as %s.""" % (name, name)
Python's str. format() method of the string class allows you to do variable substitutions and value formatting. This lets you concatenate elements together within a string through positional formatting.
Use the translate() method to replace multiple different characters. You can create the translation table specified in translate() by the str. maketrans() . Specify a dictionary whose key is the old character and whose value is the new string in the str.
%s is used as a placeholder for string values you want to inject into a formatted string. %d is used as a placeholder for numeric or decimal values. For example (for python 3) print ('%s is %d years old' % ('Joe', 42))
"f" stands for floating point. The integer (here 3) represents the number of decimals after the point. "%. 3f" will print a real number with 3 figures after the point. – Kefeng91.
Use a dictionary instead.
var = '%(foo)s %(foo)s %(foo)s' % { 'foo': 'look_at_me_three_times' }
Or format
with explicit numbering.
var = '{0} {0} {0}'.format('look_at_meeee')
Well, or format
with named parameters.
var = '{foo} {foo} {foo}'.format(foo = 'python you so crazy')
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