본문 바로가기
학부 생활 + 랩실/Python

파이썬(2) - 문자열 타입

by 프롭 2026. 4. 2.

 

문자열 타입

 

  • 문자열 데이터 생성

파이썬에서는 문자열을 매우 쉽게 다룰 수 있다. 문자열은 간단하게 ""나 ''사이에 문자를 쓰면 된다.

string1 = "ABC"
string2 = 'ABC'
print(type(string1), type(string1)) # <class 'str'> <class 'str'>
# 문자열 안에 따옴표(', ") 입력
print("Hello 'World'") # Hello 'World'
print('Hello "World"') # Hello "World"
# 특수문자 입력
print("ABC \" Hello \'World \nDEF") # ABC " Hello 'World (enter) DEF
# 한글도 잘 나온다.
print("안녕? 파이썬") # 안녕? 파이썬
 
  • 0열 선택0열 다음에 열 추가
  • 1열 선택1열 다음에 열 추가
  • 0행 선택0행 다음에 행 추가
  • 1행 선택1행 다음에 행 추가
  • 2행 선택2행 다음에 행 추가
  • 3행 선택3행 다음에 행 추가
  • 4행 선택4행 다음에 행 추가
  • 5행 선택5행 다음에 행 추가
셀 전체 선택
열 너비 조절
행 높이 조절
symbol
meaning
\n
line break
tab
들여쓰기
\\
back slash(\)
\’
quote(')
\"
double quote(")
  • 셀 병합
  • 행 분할
  • 열 분할
  • 너비 맞춤
  • 삭제

 

  • 문자열 연산

파이썬에서 문자열에 작동하는 연산자가 존재한다. +를 쓰면 문자열을 이어붙일 수 있고 *를 쓰면 문자열을 반복할 수 있다.

print("Hello World "*3) # Hello World Hello World Hello World 
print('A'+"B"+'C'+"D"*3) # ABCDDD
 

 

  • 인덱싱과 슬라이싱

문자열을 배열과 같이 보고 특정 인덱스(index)의 문자를 출력하는 것을 인덱싱, 특정 인덱스 범위의 문자열을 추출하는 것을 슬라이싱(slicing)이라 한다. 슬라이싱은 시작 인덱스:끝 인덱스로 범위를 지정하면 시작 인덱스 <= i < 끝 인덱스 범위의 문자열을 가져오게된다.

시작 인덱스가 생력되어 있으면 처음부터 가져오는 것이고 끝 인덱스가 생략되어 있으면 끝까지 가져오는 것이다. 인덱스를 뒤에서부터 셀 경우 0이 아닌 -1부터 시작하며 음수로 표현한다.

text = "ABC DEF GHI Hello World"
# ABC DEF GHI Hello World
# 0         1         2
# 01234567890123456789012
print("index t:", text[1], text[6], text[21], text[-2])
print("slice 'ABC':", text[:3])
print("slice 'GHI':", text[8:11])
print("slice 'Hello World':", text[12:])
print("slice 'Wor':", text[18:-2])
 

출력 :

index t: B F l l

slice 'ABC': ABC

slice 'GHI': GHI

slice 'Hello World': Hello World

slice 'Wor': Wor

 

  • 문자열 포매팅(Formatting)

C언어에서 %02d를 하듯 파이썬에서도 문자열에 데이터를 특정 형식으로 넣을 수 있다.

세 가지 문자열 포매팅이 존재한다.

 

1. 포맷 코드를 이용한 방법

C언어의 printf와 비슷한 방식을 포매팅을 한다. 포맷 코드를 지정해줘야하는 불편함이 있다. 파이썬에서 변수들은 동적 타입이기 때문에 변수를 특정 타입으로만 입력할 수 있다는 것은 잠재적 에러 요인이 된다.

포매팅 방법은 문자열에 포맷 코드를 넣고 문자열 옆에 %를 쓴 후 값이나 변수명을 쓰면 그 값이 포맷 코드로 들어간다. 포맷 코드는 C언어와 마찬가지로 문자열은 %s, 정수형은 %d, 실수형은 %f를 쓴다.

_class = "Assassin"
print("class: %s, HP: %d, DPS: %f" % (_class, 50, 1500.23))
 

출력 : class: Assassin, HP: 50, DPS: 1500.230000

이는 python2에서 자주 사용한 방식 보다는 다른 방식을 더 많이 쓴다.

 

2. format 함수를 이용한 방법

python 3에는 str 타입에 내장된 format() 함수가 있다. 문자열 내부에 {}가 있으면 이를 외부 데이터가 들어올 자리로 인식하고 format() 함수를 통해 데이터 값을 받는다. 이 방법의 장점은 어떤 데이터 타입이든 상관없이 brace에 자동으로 입력된다.{} 안에는 format(arg) 함수의 인자가 따로 print(arg)처럼 문자열이 들어간다.

print("class: {}, HP: {}, DPS: {}" .format(_class, 50, 1500.23))
 

출력 : class: Assassin, HP: 50, DPS: 1500.23

 

3. f문자열 포매팅

포맷 코드보다 format() 함수가 쓰기는 더 쉽지만 brace가 많아지면 몇 번째 인자인지 헷갈릴 수 있다.(format 함수에 숫자나 별명으로 더 명시적으로 작성하는 방법도 있긴하다) Python 3.6에서부터는 f문자열 포매팅을 지원하여 더 직관적으로 문자열에 데이터를 삽입하는 방법이 있다. f"{var}" 처럼 문자열 앞에 f를 붙이고 brace 사이에 변수명이나 값을 넣는 것이다.

print(f"class: {_class}, HP: {50}, DPS: {1500.23}")
 

출력 : class: Assassin, HP: 50, DPS: 1500.23

 

  • 문자열 함수

파이썬은 built-in 타입이라도 클래스 객체로 구현이 되어 있고 특히 str 클래스는 유용한 내장 함수들이 많다. 문자열 자체에서 함수 실행도 가능하다.

count() 함수를 통해 문자열 함수를 사용해보겠다.

print("ABC ABC DEF DEF ABC".count('ABC')) # 3
text = "ABC ABC DEF DEF ABC"
print(text.count('DEF')) # 2
 

이 외에도 다양한 함수들이 있다.

find(), index() : 전체 문자열 내부에 입력 받은 문자열이 어디 있는지 앞에서부터 찾아서 인덱스를 반환한다.

이 두 함수의 차이는 입력 문자열을 못 찾앗을 때의 처리 방법이다.

find()는 -1을 반환하고 index() 에러를 낸다. 그렇기에 이에 맞는 예외 처리를 해줘야한다.

text = "ABC ABC DEF DEF ABC"
find_text = text.find("ABC")
print(f"'ABC' found at {find_text} in '{text}'")
find_text = text.find("ABC",find_text+1)
print(f"'ABC' found at {find_text} in '{text}'")
find_text = text.find("ABC",find_text+1)
print(f"'ABC' found at {find_text} in '{text}'")
find_text = text.find("ABC",find_text+1)
print(f"'ABC' found at {find_text} in '{text}'")

index_text = text.index("ABC")
print(f"'ABC' found at {index_text} in '{text}'")
index_text = text.index("ABC",index_text+1)
print(f"'ABC' found at {index_text} in '{text}'")
index_text = text.index("ABC",index_text+1)
print(f"'ABC' found at {index_text} in '{text}'")
index_text = text.index("ABC",index_text+1)
print(f"'ABC' found at {index_text} in '{text}'")
 

출력 :

'ABC' found at 0 in 'ABC ABC DEF DEF ABC'

'ABC' found at 4 in 'ABC ABC DEF DEF ABC'

'ABC' found at 16 in 'ABC ABC DEF DEF ABC'

'ABC' found at -1 in 'ABC ABC DEF DEF ABC'

'ABC' indexed at 0 in 'ABC ABC DEF DEF ABC'

'ABC' indexed at 4 in 'ABC ABC DEF DEF ABC'

'ABC' indexed at 16 in 'ABC ABC DEF DEF ABC'

'ABC' not indexed, value error: substring not found

 

upper(), lower() : 문자열끼리 ==을 통해 비교할 때 대소문자가 다르면 다른 문자로 인식한다. 이를 무시하고 비교하고 싶은 경우 모두 대문자나 소문자로 통일 후 비교하면 된다.

print("uppper and lower case")
mixed = "AbC"
small = "abc"
print(f"compare {mixed} and {small}")
print(f"{mixed} == {small}:", mixed == small)
print(f"{mixed}.lower() == {small}:", mixed.lower() == small)
print(f"{mixed}.upper() == {small}.upper():", mixed.upper() == small.upper())
print(f"{mixed}.lower() is {small}.lower():", mixed.lower() is small.lower())
 

출력 :

uppper and lower case

compare AbC and abc

AbC == abc: False

AbC.lower() == abc: True

AbC.upper() == abc.upper(): True

AbC.lower() is abc.lower(): False

 

strip(), lstrip(), rstrip() : 공백이나 불필요한 시작 / 끝 문자 지우기 문자열을 다루다 보면 문자열에 불필요한 기호나 공백들이 앞이나 끝에 붙을 때가 있다. 이때 이러한 것들을 제거해주는 함수가 strip이다. 입력 인자를 넣지 않으면 자동으로 공백을 제거하고 입력 문자열을 넣으면 그 문자열을 삭제한다. 문자열 앞쪽에서만 지우고 싶을때는 lstrip()을 문자열 뒤쪽만 지우고 싶을 때는 rstrip()을 쓴다.

wise_saying = ' "Walking on water and developing software ' \
              'from a specification are easy if both are frozen..." '
print(wise_saying)
wise_saying = wise_saying.strip()
print(wise_saying)
wise_saying = wise_saying.strip('\"')
print(wise_saying)
wise_saying = wise_saying.rstrip('.')
print(wise_saying)
 

출력 :

"Walking on water and developing software from a specification are easy if both are frozen..."

"Walking on water and developing software from a specification are easy if both are frozen..."

Walking on water and developing software from a specification are easy if both are frozen...

Walking on water and developing software from a specification are easy if both are frozen

 

replace() : 문자열 바꾸기 말 그대로 문자열 안의 특정 문자열을 다른 문자열로 교체하는 함수다. strip은 양 끝에 있는 것만을 지울 수 있어서 중간에 있는 것을 지울 때는 replace()를 쓴다.

Lincoln_said = "for the people, by the people, of the people"
We_say = Lincoln_said.replace("people", "python")
Simply_say = We_say.replace("the ", "")
print("Lincoln said:", Lincoln_said)
print("We say:", We_say)
print("Simply say:", Simply_say)
 

출력 :

Lincoln said: for the people, by the people, of the people

We say: for the python, by the python, of the python

Simply say: for python, by python, of python

 

split() : 문자열 나누기, 문자열을 특정 문자열을 기준으로 나눠서 문자열의 list로 출력하는 함수다.

print("split by words:", We_say.split(" "))
print("split by phrase:", We_say.split(","))
 
 

출력 :

split by words: ['for', 'the', 'python,', 'by', 'the', 'python,', 'of', 'the', 'python']

split by phrase: ['for the python', ' by the python', ' of the python']