파이썬에서의 문자열 조작

파이썬에서의 문자열 조작

이 글은 파이썬에서 문자열을 조작하는 방법을 설명합니다.

문자열 생성과 연결, 검색 및 교체와 같은 다양한 문자열 조작 방법을 코드 샘플과 함께 배울 수 있습니다.

YouTube Video

파이썬에서의 문자열 조작

파이썬에서 문자열을 조작하는 다양한 방법이 있습니다. 아래는 자주 사용되는 문자열 연산에 대한 소개입니다.

문자열 생성

파이썬에서는 문자열을 작은따옴표('), 큰따옴표("), 또는 삼중따옴표(''', """)를 사용하여 생성할 수 있습니다.

1single_quoted = 'Hello'
2double_quoted = "World"
3multi_line = '''This is
4a multi-line
5string'''
6
7print(single_quoted)
8print(double_quoted)
9print(multi_line)
  • 이 코드는 파이썬에서 작은따옴표, 큰따옴표, 삼중따옴표를 사용하여 문자열을 생성하고 출력하는 방법을 보여줍니다.

문자열 연결

문자열을 연결하려면 + 연산자, f-strings, 또는 str.format 메서드를 사용하세요.

 1# + operator
 2name = "John"
 3greeting = "Hello, " + name + "!"
 4print(greeting)
 5
 6# f-string (available in Python 3.6 and above)
 7greeting_f = f"Hello, {name}!"
 8print(greeting_f)
 9
10# str.format method
11greeting_format = "Hello, {}!".format(name)
12print(greeting_format)
  • 이 코드는 파이썬에서 + 연산자, f-string, 그리고 str.format 메서드를 사용하여 문자열을 연결하는 방법을 보여줍니다.

문자열 반복

문자열을 반복하려면 * 연산자를 사용하세요.

1repeat = "ha" * 3  # Result: "hahaha"
2print(repeat)
  • 이 코드는 파이썬에서 * 연산자를 사용하여 문자열을 반복하는 방법을 보여줍니다.

문자열 길이

문자열의 길이를 구하려면 len 함수를 사용하세요.

1name = "John"
2greeting = "Hello, " + name + "!"
3
4# Returns the length of the string greeting
5length = len(greeting)
6print(length)
  • 이 코드는 파이썬에서 len 함수를 사용하여 문자열의 길이를 구하는 방법을 보여줍니다.

인덱싱과 슬라이싱

문자열 내 특정 문자나 부분 문자열을 얻으려면 인덱싱 또는 슬라이싱을 사용하세요.

 1word = "Python"
 2
 3first_char = word[0]    # P
 4last_char = word[-1]    # n
 5print(first_char)
 6print(last_char)
 7
 8# Slice
 9sliced_word = word[1:4] # yth
10reversed_word = word[::-1] # nohtyP
11print(sliced_word)
12print(reversed_word)
  • 이 코드는 파이썬에서 인덱싱과 슬라이싱을 사용하여 문자열에서 특정 문자나 부분 문자열을 추출하는 방법을 보여줍니다.

각 문자 처리하기

문자열은 시퀀스 타입으로 취급되므로 for 루프를 사용하여 각 문자를 처리할 수 있습니다.

1text = "Python"
2
3# Iterate each character
4for char in text:
5    print(char)
  • {^ i18n_speak このコードは、文字列 Python を1文字ずつ取り出して順番に表示する方法を示しています。^}

문자열 검색 및 교체

문자열을 검색하고 교체하려면 str.findstr.replace 메서드를 사용하세요.

1sentence = "She sells sea shells on the sea shore."
2
3# Returns the index of the first occurrence of "sea": 10
4index = sentence.find("sea")
5print(index)
6
7# Replace "sea" with "ocean"
8replaced_sentence = sentence.replace("sea", "ocean")
9print(replaced_sentence)
  • 이 코드는 파이썬에서 str.find 메서드를 사용하여 문자열을 검색하고 str.replace 메서드를 사용하여 문자열을 교체하는 방법을 보여줍니다.

문자열 대소문자 변환

문자열을 대문자 또는 소문자로 변환하려면 str.upper, str.lower, str.capitalize, 또는 str.title을 사용하세요.

 1text = "hello world"
 2upper_text = text.upper()       # "HELLO WORLD"
 3lower_text = text.lower()       # "hello world"
 4capitalized_text = text.capitalize() # "Hello world"
 5title_text = text.title()       # "Hello World"
 6
 7print(upper_text)
 8print(lower_text)
 9print(capitalized_text)
10print(title_text)
  • 이 코드는 파이썬에서 문자열을 대문자, 소문자, 타이틀 케이스로 변환하는 방법을 보여줍니다.

문자열 분리 및 결합

특정 구분자로 문자열을 분리하려면 str.split을 사용하고, 리스트 요소들을 결합하려면 str.join을 사용하세요.

1csv = "apples,bananas,cherries"
2fruits = csv.split(",")  # ["apples", "bananas", "cherries"]
3joined_fruits = ", ".join(fruits)  # "apples, bananas, cherries"
4
5print(fruits)
6print(joined_fruits)
  • 이 코드는 파이썬에서 str.split를 사용하여 문자열을 분할하고 str.join을 사용하여 리스트 요소를 연결하는 방법을 보여줍니다.

공백 제거

문자열의 공백을 제거하려면 str.strip, str.lstrip, 또는 str.rstrip을 사용하세요.

1whitespace = "   hello   "
2stripped = whitespace.strip()   # "hello"
3lstripped = whitespace.lstrip() # "hello   "
4rstripped = whitespace.rstrip() # "   hello"
5
6print(stripped)
7print(lstripped)
8print(rstripped)
  • 이 코드는 파이썬에서 str.strip, str.lstrip, str.rstrip을 사용하여 문자열의 앞뒤 또는 양쪽의 공백을 제거하는 방법을 보여줍니다.

요약

이러한 연산을 결합하면 Python에서 다양한 문자열 조작을 수행할 수 있습니다.

위의 기사를 보면서 Visual Studio Code를 사용해 우리 유튜브 채널에서 함께 따라할 수 있습니다. 유튜브 채널도 확인해 주세요.

YouTube Video