Anake
Anake

Reputation: 7649

Python - decimal places (putting floats into a string)

I have been using the format:

print 'blah, blah %f' %variable

to put variables into strings. I heard it was more pythonic than the '+str()+' approach, and have got quite used to it. Is there a way of specifying the decimal places added to the string with %f? I have tried rounding the number before supplying the variable.

Thanks

Upvotes: 7

Views: 34349

Answers (3)

Johann
Johann

Reputation: 661

For Python version 3.6 and upwards there is also the option to use f-strings, which works in a quite similar fashion to what Kirk Strauser showed in his answer

print(f'blah, blah {variable:.2f}')

Upvotes: 3

Kirk Strauser
Kirk Strauser

Reputation: 30947

In Python version 2.6 and newer, you can use:

>>> print('blah, blah {0:.2f}'.format(variable))

where "0" refers to the first value passed into str.format, ":" says "here comes the format specification", and ".2f" means "floating point number with two decimal places of precision". This is the suggested way of formatting strings now.

Upvotes: 6

Jacob
Jacob

Reputation: 43229

>>> variable = 12
>>> print 'blah, blah %4.3f' %variable
blah, blah 12.000
>>> print 'blah, blah %1.1f' %variable
blah, blah 12.0

Here is the Python Doc Link, please consider:

Since str.format() is quite new, a lot of Python code still uses the % operator. However, because this old style of formatting will eventually be removed from the language, str.format() should generally be used.

Upvotes: 12

Related Questions