코딩, 개발에 대한 기록 저장소

파이썬(Python) 숫자 표현 포멧 - 숫자를 표현하는 다양한 방법


## 파이썬(Python) 숫자 표현 포멧 - 숫자를 다양하게 표현하는 방법

파이썬은 print 함수를 사용해 숫자 형식을 다양하게 표현을 할 수 있음

### print 함수의 기본 표현 포멧
```python
# 3자리수 콤마
print("{0:,}".format(12345))

# +/- 표시
print("{0:+}".format(12345))
print("{0:+}".format(-12345))

# 소수점 특정 자리수까지만 표시
print("{0:.2f}".format(3.14159))

# 오른쪽 정렬(10자리 공간)
print("{0: >10}".format(123))

# 왼쪽 정렬(10자리 공간, 빈 칸은 _으로 채움)

print("{0:_<10}".format(123))
```
결과
```python
12,345
+12345
-12345
3.14
       123
123_______
```

### 포멧 조합으로 다양한 숫자 표현
```python
# +/- 표시, 오른쪽 정렬(10자리 공간)
print("{0: >+10}".format(123))
print("{0: >+10}".format(-123))

#3자리수 콤마, +/-부호, 오른쪽 정렬(10자리 공간)
print("{0:>+10,}".format(12345))

#3자리수 콤마, +/-부호, 왼쪽 정렬(10자리 공간, 빈 칸은 _으로 채움)
print("{0:_<+10,}".format(12345))
```
결과
```python
      +123
      -123
   +12,345
+12,345___
&#61095; 
```

### 숫자 앞에 0 채우기
```python
n1=1; n2=12; n3=123

print(str(n1).zfill(5))
print(str(n2).zfill(5))
print(str(n3).zfill(5))
```
결과
```python
00001
00012
00123
```