views:

2382

answers:

7

I need to find out how to format numbers as strings. My code is here:

return str(hours)+":"+str(minutes)+":"+str(seconds)+" "+ampm

Hours and minutes are integers, and seconds is a float. the str() function will convert all of these numbers to the tenths (0.1) place. So instead of my string outputting "5:30:59.07 pm", it would display something like "5.0:30.0:59.1 pm".

Bottom line, what library / function do I need to do this for me?

+19  A: 

Formatting in Python is done via the string formatting (%) operator:

"%02d:%02d:%02d" % (hours, minutes, seconds)

/Edit: There's also strftime.

Konrad Rudolph
+2  A: 

This is the Python documentation page on string formatting, I think it would be a good place to start: http://docs.python.org/lib/typesseq-strings.html

Theo
+2  A: 

You can use C style string formatting:

"%d:%d:d" % (hours, minutes, seconds)

See here, especially: http://diveintopython.org/native_data_types/formatting_strings.html

swilliams
A: 

See here: http://docs.python.org/lib/typesseq-strings.html

Weeble
A: 

str() in python on an integer will not print any decimal places.

If you have a float that you want to ignore the decimal part, then you can use str(int(floatValue)).

Perhaps the following code will demonstrate:

>>> str(5)
'5'
>>> int(8.7)
8
Matthew Schinckel
+2  A: 

Starting in Python 2.6., there is an alternative: the str.format() method. Here are some examples using the existing string format operator (%):

>>> "Name: %s, age: %d" % ('John', 35) 
'Name: John, age: 35' 
>>> i = 45 
>>> 'dec: %d/oct: %#o/hex: %#X' % (i, i, i) 
'dec: 45/oct: 055/hex: 0X2D' 
>>> "MM/DD/YY = %02d/%02d/%02d" % (12, 7, 41) 
'MM/DD/YY = 12/07/41' 
>>> 'Total with tax: $%.2f' % (13.00 * 1.0825) 
'Total with tax: $14.07' 
>>> d = {'web': 'user', 'page': 42} 
>>> 'http://xxx.yyy.zzz/%(web)s/%(page)d.html' % d 
'http://xxx.yyy.zzz/user/42.html' 

Here are the equivalent using str.format():

>>> "Name: {0}, age: {1}".format('John', 35) 
'Name: John, age: 35' 
>>> i = 45 
>>> 'dec: {0}/oct: {0:#o}/hex: {0:#X}'.format(i) 
'dec: 45/oct: 0o55/hex: 0X2D' 
>>> "MM/DD/YY = {0:02d}/{1:02d}/{2:02d}".format(12, 7, 41) 
'MM/DD/YY = 12/07/41' 
>>> 'Total with tax: ${0:.2f}'.format(13.00 * 1.0825) 
'Total with tax: $14.07' 
>>> d = {'web': 'user', 'page': 42} 
>>> 'http://xxx.yyy.zzz/{web}/{page}.html'.format(**d) 
'http://xxx.yyy.zzz/user/42.html'

Like Python 2.6+, all Python 3 releases (so far) understand how to do both.

wescpy
A: 

If you have a value that includes a decimal, but the decimal value is negligible (ie: 100.0) and try to int that, you will get an error. It seems silly, but calling float first fixes this.

str(int(float([variable])))

Ruz
@Ruz: how's your "answer" related to the question?
SilentGhost