3

I have been aware of .format for a long while now but when I tried to include float formatting in a string like below:

"ab_{}_cd{}_e_{}_{}_{}_val={0:.5f}_{}".format(string1,str(2),string2,string3,string4,str(0.12345678),string5)

In the above example string1-5 denote random strings included for this example.

Returned the following error ValueError: cannot switch from automatic field numbering to manual field specification

After some searching this question does seem to hold the solution Using .format() to format a list with field width arguments

The above link shows I need to format all of the {} in the string to achieve the formatting I want. I have glanced at official documentation https://docs.python.org/2/library/string.html and https://docs.python.org/2/library/stdtypes.html#str.format and there isn't much in the way of explaining what I'm looking for.

Desired output:

An explanation as to how I can convert the automatic field specification of the .format option to a manual field specification with only formatting the float variable I have supplied and leaving all other string1-5 variables unformatted. Whilst I could just use something like round() or a numpy equivalent this might cause issues and I feel like I would learn better with the .format example.

cd123
  • 511
  • 1
  • 5
  • 15
  • I think you are misunderstanding the error message. `{0:.5f}` means "take zeroth argument and format it as `.5f`". (The error message tells you that if you refer to a positional argument by its ordinal number, then you need to refer to _all_ positional arguments by their ordinal numbers.) Did you mean something like `{:0.5f}` instead? Also, for the `f` format to work, your next-to-last argument should not be a string, but an actual float. – user4815162342 May 21 '18 at 10:21

1 Answers1

4

in your code remove the zero before the rounded digit

"ab_{}_cd{}_e_{}_{}_{}_val={:.5f}_{}".format(string1,str(2),string2,string3,string4,str(0.12345678),string5)

NOTE: why it did not work is , you can either mention index in {} as {0},{1} or leave all of them, but you cannot keep few {} with index and few without any index.

rawwar
  • 4,834
  • 9
  • 32
  • 57