Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

string.format() with optional placeholders

Tags:

I have the following Python code (I'm using Python 2.7.X):

my_csv = '{first},{middle},{last}' print( my_csv.format( first='John', last='Doe' ) ) 

I get a KeyError exception because 'middle' is not specified (this is expected). However, I want all of those placeholders to be optional. If those named parameters are not specified, I expect the placeholders to be removed. So the string printed above should be:

John,,Doe 

Is there built in functionality to make those placeholders optional, or is some more in depth work required? If the latter, if someone could show me the most simple solution I'd appreciate it!

like image 691
void.pointer Avatar asked Jun 13 '12 20:06

void.pointer


People also ask

How do you put a placeholder on a string?

The format() method formats the specified value(s) and insert them inside the string's placeholder. The placeholder is defined using curly brackets: {}. Read more about the placeholders in the Placeholder section below. The format() method returns the formatted string.

How format () method is used for string formatting explain with examples?

Method 2: Formatting string using format() method Formatters work by putting in one or more replacement fields and placeholders defined by a pair of curly braces { } into a string and calling the str.

How do you replace a placeholder in a string in Python?

Python String format() is a function used to replace, substitute, or convert the string with placeholders with valid values in the final string. It is a built-in function of the Python string class, which returns the formatted string as an output.

What is %s in string format?

The %s operator is put where the string is to be specified. The number of values you want to append to a string should be equivalent to the number specified in parentheses after the % operator at the end of the string value.


2 Answers

Here is one option:

from collections import defaultdict  my_csv = '{d[first]},{d[middle]},{d[last]}' print( my_csv.format( d=defaultdict(str, first='John', last='Doe') ) ) 
like image 184
Andrew Clark Avatar answered Oct 12 '22 20:10

Andrew Clark


"It does{cond} contain the the thing.".format(cond="" if condition else " not") 

Thought I'd add this because it's been a feature since the question was asked, the question still pops up early in google results, and this method is built directly into the python syntax (no imports or custom classes required). It's a simple shortcut conditional statement. They're intuitive to read (when kept simple) and it's often helpful that they short-circuit.

like image 38
roundar Avatar answered Oct 12 '22 19:10

roundar