3

I want to use format specifier on numbers in string

Alist = ["1,25,56.7890,7.8"]

tokens = Alist[0].split(',')

for number in tokens:
    print "%6.2f" %number ,

Outcome: It gives me error.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
user2848250
  • 35
  • 1
  • 1
  • 3
  • In your example, just to write `print number` instead of `print "%6.2f" %number` would be the most obvious solution, but what is it, that you want to do in the end (I'm guessing you don't just want to print the numbers, or?)? And are you sure you need to format the strings to numbers to archieve your goal? If you are, int() for integers or float() for floats should work. – Sitses Oct 10 '13 at 22:09
  • 1
    Try `print "%6.2f" % float(number)` – Fredrik Pihl Oct 10 '13 at 22:11
  • Or look at http://stackoverflow.com/questions/455612/python-limiting-floats-to-two-decimal-points – lordkain Oct 10 '13 at 22:12
  • 1
    You have a string, after splitting you have a list of strings; to treat those strings as numbers requires you to convert them to numbers *first*. – Martijn Pieters Oct 10 '13 at 22:12

1 Answers1

3

TypeError: float argument required, not str

Your error clearly states that you are trying to pass a String off as a Float.

You must cast your string value to a float:

for number in tokens: 
    print '{:6.2f}'.format(float(number))

Note If you are using a version of python earlier than 2.6 you cannot use format()
You will have to use the following:

print '%6.2f' % (float(number),) # This is ugly.

Here is some documentation on Python 2.7 format examples.

Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132
  • Good catch. I must have copied my old for loop. – Mr. Polywhirl Oct 10 '13 at 22:36
  • No worries. I fixed up your old-style one as well (removed the period before `%`). – Caleb Hattingh Oct 10 '13 at 22:38
  • `format` is fine for Python 2.6 - You just can't omit the numbered parameters, so the above would have to be: `{0:6.2f}` as the format string for instance. I would also write the above as `format(float(number), '6.2f')` instead – Jon Clements Oct 10 '13 at 22:38
  • 1
    Coming from a C background, `format(value, format_spec)` looks strange to me. – Mr. Polywhirl Oct 10 '13 at 22:51
  • If something looks ugly to me in the second piece, it's the explicit tuple notation. When you say "earlier than 2.6", do you mean also that you can't do `'%6.2f' % float(number)`? Or the reason for the comment is that you just don't like the `%` operator itself? – Alois Mahdal Oct 11 '13 at 15:50