User avatar
some_evil
Posts: 205
Joined: Thu Dec 18, 2014 3:16 am
Location: Albury, Australia

Trying to understand this code...

Tue Mar 10, 2015 3:14 am

Hi All,

I have recently been setting up a Thermometer with my Pi, and I have noticed a line of code in a tutorial which I am using, but I am unsure what it is doing exactly, so I am hoping to research and have it clearer in my mind...

The line is:

Code: Select all

print 'Temp={0:0.1f}*C  Humidity={1:0.1f}%'.format(t,h)
I am used to doing this type of thing:

Code: Select all

print 'Hi, My name is %s and my age is %s years' % (name,age)
but this stuff with the curly brackets and .format has me stumped.

Can anyone please either explain what the code is doing in my first example? Or give me something I can google to research myself?

Thanks very much for your time.
PiZeroW - May 2017
Pi 3 - Oct 2016
PiZero - June 2016
Pi 2 - Jan 2016
Pi B+ - Dec 25 2014

User avatar
Douglas6
Posts: 4874
Joined: Sat Mar 16, 2013 5:34 am
Location: Chicago, IL

Re: Trying to understand this code...

Tue Mar 10, 2015 3:43 am

Format is the preferred method of doing the same thing. One, it requires more typing, and so promotes stoicism and finger strength. Two, it is more flexible, and is described fully here: https://docs.python.org/2/library/strin ... ing-syntax
Last edited by Douglas6 on Tue Mar 10, 2015 3:55 am, edited 1 time in total.

User avatar
some_evil
Posts: 205
Joined: Thu Dec 18, 2014 3:16 am
Location: Albury, Australia

Re: Trying to understand this code...

Tue Mar 10, 2015 3:55 am

Excellent, so after a quick read, I think I can pull it apart...

{0:0.1f}

the first zero is referencing the first argument (in this case it is 't')

the 0.1f is telling it that the t should be displayed to 1 decimal place. E.g. 26.5*C

is it as simple as that?
PiZeroW - May 2017
Pi 3 - Oct 2016
PiZero - June 2016
Pi 2 - Jan 2016
Pi B+ - Dec 25 2014

User avatar
Douglas6
Posts: 4874
Joined: Sat Mar 16, 2013 5:34 am
Location: Chicago, IL

Re: Trying to understand this code...

Tue Mar 10, 2015 3:58 am

Just that easy. The arguments can have names instead of indices, but frankly I've never seen it done. You can also skip the index {:0.1f} and assume a sequence.

Return to “Python”