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.
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.
%).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') insteadformat(value, format_spec) looks strange to me.'%6.2f' % float(number)? Or the reason for the comment is that you just don't like the % operator itself?
print numberinstead ofprint "%6.2f" %numberwould 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.print "%6.2f" % float(number)