문제

주어진:

a = 1
b = 10
c = 100

2 자리 미만의 모든 숫자에 대해 주요 0을 표시하려면 어떻게해야합니까?

그건,

01
10
100
도움이 되었습니까?

해결책

Python 2에서는 할 수 있습니다.

print "%02d" % (1,)

원래 % 처럼 printf 또는 sprintf.


파이썬 3의 경우+ 동일한 동작을 다음과 같이 달성 할 수 있습니다.

print("{:02d}".format(1))

Python 3.6+의 경우 F- 스트링으로 동일한 동작을 달성 할 수 있습니다.

print(f"{1:02d}")

다른 팁

당신이 사용할 수있는 str.zfill:

print str(1).zfill(2) 
print str(10).zfill(2) 
print str(100).zfill(2) 

인쇄물:

01
10
100

Python 2.6+ 및 3.0+에서는 format() 문자열 방법 :

for i in (1, 10, 100):
    print('{num:02d}'.format(num=i))

또는 내장을 사용하여 (단일 번호) :

print(format(i, '02d'))

참조 PEP-3101 새로운 형식 기능에 대한 문서.

print('{:02}'.format(1))
print('{:02}'.format(10))
print('{:02}'.format(100))

인쇄물:

01
10
100

아니면 이거:

print '{0:02d}'.format(1)

~ 안에 파이썬> = 3.6, 당신은 다음을 사용하여 소개 된 새로운 F- 스트링으로 간결하게 할 수 있습니다.

f'{val:02}'

변수를 이름으로 인쇄합니다 val a fill 가치 0 그리고 a width2.

특정 예제의 경우 루프 에서이 작업을 멋지게 수행 할 수 있습니다.

a, b, c = 1, 10, 100
for val in [a, b, c]:
    print(f'{val:02}')

어떤 인쇄 :

01 
10
100

F- 스트링에 대한 자세한 내용은 PEP 498 그들이 소개 된 곳.

x = [1, 10, 100]
for i in x:
    print '%02d' % i

결과 :

01
10
100

읽다 % 사용 문자열 서식에 대한 자세한 정보 문서에서.

The Pythonic way to do this:

str(number).rjust(string_width, fill_char)

This way, the original string is returned unchanged if its length is greater than string_width. Example:

a = [1, 10, 100]
for num in a:
    print str(num).rjust(2, '0')

Results:

01
10
100

Or another solution.

"{:0>2}".format(number)

Use a format string - http://docs.python.org/lib/typesseq-strings.html

For example:

python -c 'print "%(num)02d" % {"num":5}'
width = 5
num = 3
formatted = (width - len(str(num))) * "0" + str(num)
print formatted

This is how I do it:

str(1).zfill(len(str(total)))

Basically zfill takes the number of leading zeros you want to add, so it's easy to take the biggest number, turn it into a string and get the length, like this:

Python 3.6.5 (default, May 11 2018, 04:00:52) 
[GCC 8.1.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> total = 100
>>> print(str(1).zfill(len(str(total))))
001
>>> total = 1000
>>> print(str(1).zfill(len(str(total))))
0001
>>> total = 10000
>>> print(str(1).zfill(len(str(total))))
00001
>>> 

Use:

'00'[len(str(i)):] + str(i)

Or with the math module:

import math
'00'[math.ceil(math.log(i, 10)):] + str(i)
s=1    
s="%02d"%s    
print(s)

the result will be 01

If dealing with numbers that are either one or two digits:

'0'+str(number)[-2:] or '0{0}'.format(number)[-2:]

!/usr/bin/env python3

Copyright 2009-2017 BHG http://bw.org/

x = 5

while (x <= 15):
    a =  str("{:04}".format(x))
    print(a)
    x = x + 1;

same code as an image

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top