cd123
cd123

Reputation: 521

python .format including float formatting

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.

Upvotes: 3

Views: 1809

Answers (1)

rawwar
rawwar

Reputation: 4992

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.

Upvotes: 4

Related Questions