본문 바로가기
Python/파이썬 기초

파이썬 문자열 타입 (str)

by PySun 2023. 7. 25.
반응형

 
파이썬에서 문자열(str)을 표현하는 방법과 문자열에 대한 다양한 연산 및 처리 방법에 대해 예시 코드로 설명하겠습니다.

1. 따옴표 사용법

  • 파이썬에서 문자열은 작은따옴표('')나 큰따옴표("")로 감싸서 표현할 수 있습니다. 두 가지 모두 문자열을 나타내는 데에 사용되며, 사용 방법에는 차이가 없습니다. 선택한 따옴표로 문자열을 감싸면 됩니다.
# 작은따옴표를 사용한 문자열
single_quoted_string = 'Hello, Python!'

# 큰따옴표를 사용한 문자열
double_quoted_string = "Welcome to Python!"

2. 문자열 연산방법

  • 파이썬에서는 문자열끼리의 연산이 가능합니다. 덧셈과 곱셈이 주로 사용되며, 덧셈은 두 문자열을 이어붙이고, 곱셈은 문자열을 반복합니다.
# 문자열 덧셈
string1 = "Hello, "
string2 = "Python!"
concatenated_string = string1 + string2
print(concatenated_string)  # 출력: "Hello, Python!"

# 문자열 곱셈
repeated_string = "Python! " * 3
print(repeated_string)  # 출력: "Python! Python! Python! "

3. 문자열 인덱싱(indexing)과 슬라이싱(slicing)

  • 문자열에서 특정 위치의 문자를 가져오는 인덱싱과 부분 문자열을 추출하는 슬라이싱이 가능합니다. 파이썬의 인덱싱은 0부터 시작하며, 음수 인덱스는 뒤에서부터 역순으로 접근합니다.
# 문자열 인덱싱
text = "Python"
print(text[0])  # 출력: "P"
print(text[-1])  # 출력: "n"

# 문자열 슬라이싱
substring = text[1:4]
print(substring)  # 출력: "yth"

4. 문자열 포매팅(formatting)

  • 문자열 포매팅은 문자열 내에 변수 값을 삽입하여 동적인 문자열을 만드는 방법입니다. 이를 위해 % 연산자, format() 메서드, f-string 등 다양한 방법이 있습니다.
# 문자열 포매팅 - 방법 1: %
name = "Alice"
age = 30
formatted_string = "My name is %s and I am %d years old." % (name, age)
print(formatted_string)  # 출력: "My name is Alice and I am 30 years old."

# 문자열 포매팅 - 방법 2: format() 메서드
animal = "dog"
color = "brown"
formatted_string = "The {0} is {1}.".format(animal, color)
print(formatted_string)  # 출력: "The dog is brown."

# 문자열 포매팅 - 방법 3: f-string (파이썬 3.6 이상)
height = 175.5
name = "John"
formatted_string = f"{name}'s height is {height}cm."
print(formatted_string)  # 출력: "John's height is 175.5cm."

5. 이스케이프 문자(escape)

  • 이스케이프 문자는 특수한 의미를 가진 문자를 문자열 안에서 표현할 수 있도록 해줍니다. 주로 역슬래시 \와 함께 사용되며, 몇 가지 종류가 있습니다.
  • \n: 새로운 줄 (개행)
  • \t: 탭 문자
  • \\: 역슬래시 자체를 표현
  • \': 작은따옴표를 표현
  • \": 큰따옴표를 표현
# 이스케이프 문자 사용
escaped_string = "This is a new line\nand this is a tab\t."
print(escaped_string)
# 출력:
# "This is a new line
# and this is a tab   ."

# 원시 문자열 (Raw String) 사용: 이스케이프 문자 무시
raw_string = r"This is a new line\nand this is a tab\t."
print(raw_string)
# 출력: "This is a new line\nand this is a tab\t."

# 이스케이프 문자를 사용하지 않고 작은 따옴표와 큰 따옴표를 표현하는 다른 방법
text = "He said 'Hello'"
print(text) # 출력 : He said 'Hello'

text = 'He said "Hello"'
print(text) # 출력 : He said "Hello"

6. 문자열 함수

  • 파이썬에서 문자열은 내장 함수와 메서드를 통해 다양한 기능을 제공합니다. 아래는 문자열을 다루는 주요 함수와 메서드들의 설명과 예시입니다.
# len(): 문자열의 길이를 반환
text = "Hello, Python!"
length = len(text)
print(length)  # 출력: 14

# str(): 다른 데이터 타입을 문자열로 변환
num = 123
text = str(num)
print(text)  # 출력: "123"

# upper(): 문자열을 모두 대문자로 변환
text = "hello"
upper_text = text.upper()
print(upper_text)  # 출력: "HELLO"

# lower(): 문자열을 모두 소문자로 변환
text = "Hello"
lower_text = text.lower()
print(lower_text)  # 출력: "hello"

# count(): 특정 문자나 문자열의 등장 횟수를 세는 메서드
text = "Hello, Python!"
count_e = text.count('e')
print(count_e)  # 출력: 1

count_l = text.count('l')
print(count_l)  # 출력: 2

# replace(): 특정 문자나 문자열을 다른 문자나 문자열로 바꾸는 메서드
text = "Hello, Python!"
replaced_text = text.replace('Python', 'World')
print(replaced_text)  # 출력: "Hello, World!"

# split(): 문자열을 특정 구분자를 기준으로 나누어 리스트로 반환하는 메서드
text = "apple,banana,orange"
fruits_list = text.split(',')
print(fruits_list)  # 출력: ['apple', 'banana', 'orange']

# join(): 리스트의 문자열들을 특정 구분자를 이용하여 하나의 문자열로 합치는 메서드
fruits_list = ['apple', 'banana', 'orange']
joined_text = ','.join(fruits_list)
print(joined_text)  # 출력: "apple,banana,orange"

문자열은 파이썬에서 매우 중요한 데이터 타입이며, 프로그래밍에서 광범위하게 사용됩니다. 이러한 기본적인 사용 방법을 통해 학습자들이 문자열의 다양한 활용성을 파악하고 효과적으로 활용할 수 있도록 하시면 좋습니다. 문자열을 다양한 예시와 함께 실습하고 응용해보는 것이 학습에 도움이 될 것입니다.
 

반응형