Reputation: 35
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.
Upvotes: 3
Views: 10246
Reputation: 48693
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.
Upvotes: 3