[python] 문자열(String) By starseat 2026-01-11 17:04:56 python Post Tags # 문자열 ## 기본 사용법 - 문자열은 큰따옴표("), 작은따옴표(') 로 감싸는 방법이 있음. - 큰따옴표(") 와 작은따옴표(') 를 3개를 연슥으로 써서 표현도 가능. ```python "1. Hello World" '2. Hello World' """3. Hello World""" '''4. Hello WOrld''' ``` - 3개 연속은 여러줄을 표현하고자 할떄 사용 ```python multiline = """ Life is too short You need python """ print(multiline) ``` - * 로 몇번 표시할지도 가능 ```python sample = "python" print(sample * 2) ``` - 문자열 길이 구하기 ```python str_length_sample = "Life is too short" print(len(str_length_sample)) ``` - 문자열 인덱싱 ```python indexing_sample = "Life is too short, You need Python" print(indexing_sample[3]) ``` - 인덱싱에서 - 붙이면 뒤에서 부터 읽음 ```python print(indexing_sample[-2]) ``` - 슬라이싱: 시작위치 부터 끝 위치까지 추출 ```python print(indexing_sample[0:4]) print(indexing_sample[12:17]) print(indexing_sample[19:]) # 두번째 숫자 없으면 끝까지 print(indexing_sample[:17]) # 첫번째 숫자 없으면 시작 부터 print(indexing_sample[:]) # 둘 다 없으면 그냥 다 표시 print(indexing_sample[19:-7]) # - 도 가능, 19 에서 -8 까지를 의미 (-7 포하 x) ``` ## 포매팅 ```python print("I eat %d apples." % 3) # %d 에 숫자 대입 print("I eat %s apples." % "five") # %s 에 문자열 대입 ``` - 두개 이상 값 대입 ```python formatting_num = 3 formatting_str = "three" print("I ate %d apples. so I was sick for %s days" % (formatting_num, formatting_str)) ``` ## 문자열 포맷 코드 ```python # %s: 문자열 # %c: 문자 1개 # %d: 숫자 # %f: 부동소수 # %o: 8진수 # %x: 16진수 # %%: Literal % (문자 % 자체) ``` - % 사용 예제 ```python print("Error is %d%%." % 98) ``` - 정렬과 공백 ```python print("%10s" % "hi") # hi 가 왼쪽 8칸 공백 후 오른쪽으로 정렬됨 (hi 포함 10칸)) # ex: ' hi' print("%-10sjain" % 'hi') # hi 가 왼쪽 표시 후 8칸 공백 # ex: 'hi jane' ``` - 소수점 표시 ```python print("%0.4f" % 3.141592) # 소수점 4자리만 표시, (뒤는 반올림 되는 듯?) # ex: 3.1416 print("%10.4f" % 3.141592) # 전체 길이 10칸, 소수점 4자리 표시 # ex: ' 3.1416 ``` - format 함수 사용 ```python print("I eat {0} apples".format(3)) format_func1 = "wow!" print("I eat {0} apples. {1}".format("five", format_func1)) ``` - 명칭으로 치환 ```python print("I ate {number} apples. so I was sick for {day} days.".format(number=10, day="three")) ``` ## 정렬 ```python print("{0:<10}".format("hi")) # 왼쪽 정렬, 총 자리수 10칸 print("{0:>10}".format("hi")) # 오른쪽 정렬, 총 자리수 10칸 print("{0:^10}".format("hi")) # 가운데 정렬, 총 자리수 10칸 print("{0:=^10}".format("hi")) # 가운데 정렬, 총 자리수 10칸, 공백 대신 =로 print("{0:!^10}".format("hi")) # 가운데 정렬, 총 자리수 10칸, 공백 대신 !로 ``` Previous Post [python] 숫자(Number) Next Post [python] 리스트(List)