ProgramingTip

어디에서 가변 자릿수로 숫자를 어떻게 사용합니까?

bestdevel 2020. 12. 13. 10:23
반응형

어디에서 가변 자릿수로 숫자를 어떻게 사용합니까?


이 질문에 이미 답변이 있습니다.

앞면에 다양한 수의 패딩 0이있는 숫자 123을 표시하고 싶다고 가정 해 보겠습니다.

예를 들어, 5 자리 숫자로 표시 숫자 = 5로 표시하면 다음과 가변됩니다.

00123

6 자리로 표시 광고 다음과 같이 숫자 = 6을 사용합니다.

000123

어떻게에서 어떻게할까요?


zfill은 전세계에서 사용할 수 있습니다.

>>> '12344'.zfill(10)
0000012344

k (이 경우 10)로 만듭니다.


format()이전 스타일 ''%형식보다 선호 하는 방법으로 형식이 지정된 규격에서 사용하는 경우

>>> 'One hundred and twenty three with three leading zeros {0:06}.'.format(123)
'One hundred and twenty three with three leading zeros 000123.'

참조
http://docs.python.org/library/stdtypes.html#str.format
http://docs.python.org/library/string.html#formatstrings을

다음은 가변 너비의 예입니다.

>>> '{num:0{width}}'.format(num=123, width=6)
'000123'

채우기 문자를 변수로 사용 가능합니다.

>>> '{num:{fill}{width}}'.format(num=123, fill='0', width=6)
'000123'

'%0*d' % (5, 123)

Python 3.6 에 형식화 된 리터럴 (줄여서 "f-strings") 이 도입 됨에 따라 이제 더 간단한 구문으로 이전에 정의 된 변수에 액세스 할 수 있습니다.

>>> name = "Fred"
>>> f"He said his name is {name}."
'He said his name is Fred.'

John La Rooy가 제시 한 예는 다음과 같이있을 수 있습니다.

In [1]: num=123
   ...: fill='0'
   ...: width=6
   ...: f'{num:{fill}{width}}'

Out[1]: '000123'

print "%03d" % (43)

인쇄물

043


공용 서식 사용

print '%(#)03d' % {'#': 2}
002
print '%(#)06d' % {'#': 123}
000123

여기에 더 많은 정보 : 링크 텍스트

참고 URL : https://stackoverflow.com/questions/3228865/how-do-i-format-a-number-with-a-variable-number-of-digits-in-python

반응형