Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using .format() to print a variable string and a rounded number

I want to print something that looks like this:

Hello ¦ 7.16

This is the code I'm using

MyString = 'Hello'
MyFloat = 7.157777777
print "{}  ¦  {0:.2f}".format(MyString, MyFloat)

But I get the error:

ValueError: cannot switch from automatic field numbering to manual field specification

If I try:

MyString = 'Hello'
MyFloat = 7.157777777
print "{s}  ¦  {0:.2f}".format(MyString, MyFloat)

or str instead of s I get the error:

KeyError: 's'

Any ideas how I can print a variable string with a rounded float? Or is there something like %s that I should be using?

like image 800
Kevin Kraft Avatar asked Sep 03 '14 18:09

Kevin Kraft


People also ask

What does format () do in Python?

Format Function in Python (str. format()) is technique of the string category permits you to try and do variable substitutions and data formatting. It enables you to concatenate parts of a string at desired intervals through point data format.

How do you round a formatted string in Python?

The round() function is a built-in function available with python. It will return you a float number that will be rounded to the decimal places which are given as input. If the decimal places to be rounded are not specified, it is considered as 0, and it will round to the nearest integer.

What is str format () in Python?

The format() method formats the specified value(s) and insert them inside the string's placeholder. The placeholder is defined using curly brackets: {}. Read more about the placeholders in the Placeholder section below. The format() method returns the formatted string.


1 Answers

You are using a numbered reference in the second field; the 0 indicates you want to use the first parameter passed to str.format() (e.g. MyString), not the MyFloat value which is parameter 1.

Since you cannot use the .2f format on a string object, you get your error.

Remove the 0:

print "{}  ¦  {:.2f}".format(MyString, MyFloat)

as fields without a name or index number are auto-numbered, or use the correct number:

print "{}  ¦  {1:.2f}".format(MyString, MyFloat)

If you chose the latter, it's better to be explicit consistently and use 0 for the first placeholder:

print "{0}  ¦  {1:.2f}".format(MyString, MyFloat)

The other option is to use named references:

print "{s}  ¦  {f:.2f}".format(s=MyString, f=MyFloat)

Note the keyword arguments to str.format() there.

like image 84
Martijn Pieters Avatar answered Oct 21 '22 15:10

Martijn Pieters