1

What str.format does almost exactly I'm looking for. A functionality I would like to add to format() is to use optional keywords and for that I have to use another special character (I guess).

So str.format can do that:

f = "{ID1}_{ID_optional}_{ID2}"
f.format(**{"ID1" : " ojj", "ID2" : "makimaki", "ID_optional" : ""})
# Result: ' ojj__makimaki' #

I can't really use optional ID's. If the dictionary does not contain "ID_optional" it produces KeyError. I think it should be something like this to mark the optional ID:

f = "{ID1}_[IDoptional]_{ID2}"

Another thing: I have lot of template strings to process which are use [] rather than {}. So the best way would be to add the special characters as an argument for the format function.

So the basic question is there a sophisticated way to modify the original function? Or I should write my own format function based on str.format and regular expressions?

Prag
  • 529
  • 1
  • 6
  • 12

2 Answers2

0

You if/else and format based on whether the dic has the key or not:

f = "{ID1}_{ID_optional}_{ID2}" if "ID_optional" in d else "{ID1}_{ID2}" 

A dict lookup is 0(1) so it is cheap just to check

Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321
0

One option would be to define your own Formater. You can inherit the standard one and override get_field to return some reasonable default for your use case. See the link for some more documentation.

Sorin
  • 11,863
  • 22
  • 26