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.

4
  • 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. Commented Oct 10, 2013 at 22:09
  • 1
    Try print "%6.2f" % float(number) Commented Oct 10, 2013 at 22:11
  • Or look at stackoverflow.com/questions/455612/… Commented Oct 10, 2013 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. Commented Oct 10, 2013 at 22:12

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

5 Comments

Good catch. I must have copied my old for loop.
No worries. I fixed up your old-style one as well (removed the period before %).
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
Coming from a C background, format(value, format_spec) looks strange to me.
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?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.