Starting with Python 3.6, formatting in Python can be done using formatted string literals or f-strings:
hours, minutes, seconds = 6, 56, 33
f'{hours:02}:{minutes:02}:{seconds:02} {"pm" if hours > 12 else "am"}'
or the str.format function starting with 2.7:
"{:02}:{:02}:{:02} {}".format(hours, minutes, seconds, "pm" if hours > 12 else "am")
or the string formatting % operator for even older versions of Python, but see the note in the docs:
"%02d:%02d:%02d" % (hours, minutes, seconds)
And for your specific case of formatting time, thereโs time.strftime:
import time
t = (0, 0, 0, hours, minutes, seconds, 0, 0, 0)
time.strftime('%I:%M:%S %p', t)
Answer from Konrad Rudolph on Stack OverflowVideos
Starting with Python 3.6, formatting in Python can be done using formatted string literals or f-strings:
hours, minutes, seconds = 6, 56, 33
f'{hours:02}:{minutes:02}:{seconds:02} {"pm" if hours > 12 else "am"}'
or the str.format function starting with 2.7:
"{:02}:{:02}:{:02} {}".format(hours, minutes, seconds, "pm" if hours > 12 else "am")
or the string formatting % operator for even older versions of Python, but see the note in the docs:
"%02d:%02d:%02d" % (hours, minutes, seconds)
And for your specific case of formatting time, thereโs time.strftime:
import time
t = (0, 0, 0, hours, minutes, seconds, 0, 0, 0)
time.strftime('%I:%M:%S %p', t)
The OP & accepted answer focus on formatting time, but the OP question itself discusses formatting numbers to strings in Python. In many cases, the output requires additional data fields be included along with timestamps, all of which include formatting numbers as strings.
Below are a variety of non time-based examples of formatting numbers as strings, and different ways to do so, starting with the existing string format operator (%) which has been around for as long as Python has been around (meaning this solution is compatible across Python 1.x, 2.x, and 3.x):
>>> "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'
Starting in Python 2.6 (meaning it works for 2.x and 3.x), there is an alternative: the str.format() method. Here are the equivalent snippets to the above but 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. I shamelessly ripped this stuff straight out of my hardcore Python intro book and the slides for the Intro+Intermediate Python courses I offer from time-to-time. :-)
Aug 2018 UPDATE: Of course, now that we have the f-string feature introduced in 3.6 (only works in 3.6 and newer), we need the equivalent examples of that; yes, another alternative:
>>> name, age = 'John', 35
>>> f'Name: {name}, age: {age}'
'Name: John, age: 35'
>>> i = 45
>>> f'dec: {i}/oct: {i:#o}/hex: {i:#X}'
'dec: 45/oct: 0o55/hex: 0X2D'
>>> m, d, y = 12, 7, 41
>>> f"MM/DD/YY = {m:02d}/{d:02d}/{y:02d}"
'MM/DD/YY = 12/07/41'
>>> f'Total with tax: ${13.00 * 1.0825:.2f}'
'Total with tax: $14.07'
>>> d = {'web': 'user', 'page': 42}
>>> f"http://xxx.yyy.zzz/{d['web']}/{d['page']}.html"
'http://xxx.yyy.zzz/user/42.html'
You can use the zfill() method to pad a string with zeros:
In [3]: str(1).zfill(2)
Out[3]: '01'
The standard way is to use format string modifiers. These format string methods are available in most programming languages (via the sprintf function in c for example) and are a handy tool to know about.
To output a string of length 5:
... in Python 3.5 and above: f-strings.
i = random.randint(0, 99999)
print(f'{i:05d}')
Search for f-strings here for more details.
... Python 2.6 and above:
print '{0:05d}'.format(i)
... before Python 2.6:
print "%05d" % i
See: https://docs.python.org/3/library/string.html
"%04d" where the 4 is the constant length will do what you described.
You can read about string formatting here.
Update for Python 3:
{:04d} is the equivalent for strings using the str.format method or format builtin function. See the format specification mini-language documentation.
You could use the zfill function of str class. Like so -
>>> str(165).zfill(4)
'0165'
One could also do %04d etc. like the others have suggested. But I thought this is more pythonic way of doing this...
im new to python and trying to learn how to print the sum of a integer and a string number, i get an error that says| unsupported operand type(s) +: 'int' and 'str' | i dont know how to solve it and everything i look up only has for int + int so im wondering if i have to just convert the string to a integer and if so how would that be done but if thats not what i need to do i would also really appreciate an explanation.