1 분 소요

02-2 문자열 자료형


1. 문자열을 슬라이싱으로 나누기

a = "20230912-오늘하루 공부한 내용 정리"
year = a[:4] + "년"
month = a[4:6] + "월"
date = a[6:8] + "일"
title = a[9:]
print("일시 : "+year, month, date)
print("제목 : "+title)
일시 : 2023년 09월 12일
제목 : 오늘하루 공부한 내용 정리

2. 문자열 포매팅

a="현재 온도는 %s도 입니다." % 20
print(a)

number = 15
print("I eat {0}apples" .format(number))

number = 15
print(f"I eat {number}apples")
현재 온도는 20도 입니다.
I eat 15apples
I eat 15apples
date = "2023년 09월 30일"
title = "국어였습니다."
a = f"오늘은 {date}이고 학교에 공부한 내용은 {title}"
print(a)
오늘은 2023년 09월 30일이고 학교에 공부한 내용은 국어였습니다.
a = "문제는 %d%%.이다." % 98
print(a)
문제는 98%.이다.
number = 3
day = "three"
a = "I ate {0} apple and I was sick for {1}days. " .format(number,day)
print(a)
I ate 3 apple and I was sick for threedays. 
a = "rate is %s" % 3.342
print(a)
rate is 3.342
number = 9876655
title = "사람사는 세상"
a = f"{number}시간에 {title}이 온다."
print(a)
9876655시간에 사람사는 세상이 온다.

3. 정열과 공백

a = "rate is %10s" % 3.342
print(a)
rate is      3.342

4. 소수점 표현하기

x = 0.98766444
a = f"{x:0.3f}"
print(a)
0.988

5. 문자열 나누기 - split

a = "A|b|c|d"
print(a.split("|"))
['A', 'b', 'c', 'd']

* 문자열 포매팅


date = "2023년 09월 30일"

title = "국어였습니다."

a = f"오늘은 {date}이고 학교에 공부한 내용은 {title}"

print(a)

* 숫자로 대입하기

%d 는 정수 대입 - 3d 로 기억

%s 는 문자열 대입

%를 표시할때는 %%를 사용


"I eat %s apples." % "three"



"I eat %d apples." % 3

* 변수로 대입하기


number = 3

day = "three"

a = "I ate {0} apple and I was sick for {1}days. " .format(number,day)

print(a)

* 문자열 관련 함수들

함수 예시
문자 개수 세기 a.count(‘b’)
위치 알려 주기 1 a.find(‘b’)
위치 알려 주기 2 index
문자열 삽입 ”,”.join(‘abcd’)
소문자를 대문자로 바꾸기 a.lower()
왼쪽 공백 지우기 a.lstrip()
오른쪽 공백 지우기 a.rstrip()
양쪽 공백 지우기 a.strip()
문자열 바꾸기 a.replace(“Life”, “Your leg”)
문자열 나누기 a.split()