Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Output formatting in Python: replacing several %s with the same variable

Tags:

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) 
like image 305
alexmuller Avatar asked Aug 08 '11 13:08

alexmuller


People also ask

Which formatting method in Python allows multiple substitutions and value formatting?

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.

How do you replace multiple substrings in a string in Python?

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.

What is %d %s in Python?

%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))

What does {: 3f mean in Python?

"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.


1 Answers

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') 
like image 117
Cat Plus Plus Avatar answered Oct 07 '22 21:10

Cat Plus Plus