CHHB stroy

문자열 포매팅 본문

Python

문자열 포매팅

CHHB 2024. 6. 1. 19:35

문자열 포맷 코드

코드 설명
%s 문자열(String)
%c 문자 1개(Character)
%d 정수(Interger)
%f 부동 소수(Floating-point)
%o 8진수
%x 16진수
%% Literal % (문자 '%' 자체)

 

1. 숫자 바로 대입

a = "I eat %d apples." % 3
print(a)

결과 : I eat 3 apples.

 

2. 문자열 바로 대입

a = "I eat %s apples." % "five"
print(a)

결과 : I eat five apples.

 

3. 숫자 값을 나타내는 변수로 대입

number = 3
a = "I eat %d apples." % number
print(a)

결과 : I eat 3 apples.

 

4. 2개 이상의 값 넣기

number = 3
day = "three"
a = "I ate %d apples. so I was sick for %s days." % (number, day)

결과 : I ate 3 apples. so I was sick for three days.

 

%s 는 어떤 코드의 값이든 문자열로 변환하여 넣을 수 있다.

a = "I eat %s apples." % 3
print(a)
# 결과 :I eat 3 apples.

a = "I eat %s apples." % 3.234
print(a)
# 결과 :I eat 3.234 apples.

 

포맷 코드와 숫자 함께 사용하기

# 정렬과 공백
print("%10s" % "hi")
# 결과 :"        hi"
print("%-10sjane" % "hi")
# 결과 :"hi        jane"

# 소수점 표현하기
print("%10.4f" % 433.42134234)
# 결과 :"  433.4213"

 

number = 3
day = "three"
y = 3.42134234
name = '홍길동'
age = 30
d = {'name': '홍길동', 'age': 30}
print("I eat {0} apples".format(3))
# 결과 :I eat 3 apples
print("I eat {0} apples".format("five"))
# 결과 :I eat five apples
print("I eat {0} apples".format(number))
# 결과 :I eat 3 apples
print("I eat {0} apples. so I was sick for {1} days.".format(number, day))
# 결과 :I eat 3 apples. so I was sick for three days.
print("I eat {number} apples. so I was sick for {day} days.".format(number = 120, day = 3))
# 결과 :I eat 120 apples. so I was sick for 3 days.
print("I eat {0} apples. so I was sick for {day} days.".format(100, day = 3))
# 결과 :I eat 100 apples. so I was sick for 3 days.
print("'{0:<10}'".format("hi"))
# 결과 :'hi        '
print("'{0:>10}'".format("hi"))
# 결과 :'        hi'
print("'{0:^10}'".format("hi"))
# 결과 :'    hi    '
print("'{0:=^10}'".format("hi"))
# 결과 :'====hi===='
print("'{0:!<10}'".format("hi"))
# 결과 :'hi!!!!!!!!'
print("'{0:0.4f}'".format(y))
# 결과 :'3.4213'
print("'{0:.4f}'".format(y))
# 결과 :'3.4213'
print("'{0:10.4f}'".format(y))
# 결과 :'    3.4213'
print("'{{and}}'".format())
# 결과 :'{and}'
print(f"나의 이름은 {name}입니다. 나이는 {age}입니다.")
# 결과 :나의 이름은 홍길동입니다. 나이는 30입니다.
print(f"나는 내년이면 {age+1}살이 된다.")
# 결과 :나는 내년이면 31살이 된다.
print(f"나의 이름은 {d["name"]}입니다. 나이는 {d['age']}입니다.")
# 결과 :나의 이름은 홍길동입니다. 나이는 30입니다.
print(f"'{"hi":<10}'")
# 결과 :'hi        '
print(f"'{"hi":>10}'")
# 결과 :'        hi'
print(f"'{"hi":^10}'")
# 결과 :'    hi    '
print(f"'{"hi":=^10}'")
# 결과 :'====hi===='
print(f"'{"hi":!<10}'")
# 결과 :'hi!!!!!!!!'
print(f"'{y:0.4f}'")
# 결과 :'3.4213'
print(f"'{y:.4f}'")
# 결과 :'3.4213'
print(f"'{y:10.4f}'")
# 결과 :'    3.4213'
print(f"{{ and }}")
# 결과 :{ and }

'Python' 카테고리의 다른 글

Python 기초 문법 완벽 정리  (0) 2025.04.20
Set Type  (0) 2024.06.06
Dictionary Type  (0) 2024.06.06
tuple Type  (0) 2024.06.06
List Type  (0) 2024.06.06