w Pythonie jak przekonwertować jednocyfrową liczbę na dwucyfrowy ciąg znaków?
Więc powiedz, że mam
A = 5
Chcę go wydrukować jako ciąg znaków '05'
5 answers
print "%02d"%a
jest wariantem Pythona 2
Python 3 używa nieco bardziej wyrazistego systemu formatowania:
"{0:0=2d}".format(a)
Odpowiedni link doc dla python2 to: http://docs.python.org/2/library/string.html#format-specification-mini-language
Dla python3, to http://docs.python.org/3/library/string.html#string-formatting
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-11-03 21:29:53
a = 5
print '%02d' % a
# output: 05
Operator ' % ' nazywa się operatorem formatowanie łańcuchów , gdy jest używany z łańcuchem po lewej stronie. '%d'
jest kodem formatującym do wypisania liczby całkowitej (otrzymasz błąd typu, jeśli wartość nie jest numeryczna). Za pomocą '%2d
można określić długość, a '%02d'
można ustawić znak wypełnienia na 0 zamiast domyślnej spacji.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-08-17 19:24:35
>>> print '{0}'.format('5'.zfill(2))
05
Czytaj więcej Tutaj .
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-08-17 18:51:50
>>> a=["%02d" % x for x in range(24)]
>>> a
['00', '01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23']
>>>
It is that simple
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-02-10 10:02:05
W Python3 Możesz:
print("%02d" % a)
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-10-24 08:22:45