반응형
Python에서 문자열을 다루는 방법은 매우 다양합니다. 문자열을 생성, 조작, 검색, 변환하는 여러 가지 방법을 제공하는 풍부한 내장 메서드와 연산자가 있습니다. 다음은 Python에서 문자열을 다루는 주요 방법들입니다.
문자열 생성
s1 = "Hello, World!"
s2 = 'Python is fun'
s3 = """This is a multiline
string."""
s4 = '''This is also a
multiline string.'''
문자열 연산
연결 (Concatenation)
s1 = "Hello"
s2 = "World"
s3 = s1 + ", " + s2 + "!"
print(s3) # 출력: Hello, World!
반복 (Repetition)
s = "Python"
print(s * 3) # 출력: PythonPythonPython
문자열 인덱싱과 슬라이싱
인덱싱 (Indexing)
s = "Hello"
print(s[0]) # 출력: H
print(s[-1]) # 출력: o
슬라이싱 (Slicing)
s = "Hello, World!"
print(s[0:5]) # 출력: Hello
print(s[7:]) # 출력: World!
print(s[:5]) # 출력: Hello
print(s[::2]) # 출력: Hlo ol!
문자열 메서드
길이 (Length)
s = "Hello"
print(len(s)) # 출력: 5
대소문자 변환
s = "Hello, World!"
print(s.upper()) # 출력: HELLO, WORLD!
print(s.lower()) # 출력: hello, world!
print(s.capitalize()) # 출력: Hello, world!
print(s.title()) # 출력: Hello, World!
공백 제거
s = " Hello, World! "
print(s.strip()) # 출력: Hello, World!
print(s.lstrip()) # 출력: Hello, World!
print(s.rstrip()) # 출력: Hello, World!
문자열 검색과 치환
s = "Hello, World!"
print(s.find("World")) # 출력: 7
print(s.replace("World", "Python")) # 출력: Hello, Python!
문자열 분할과 결합
s = "Hello, World!"
print(s.split(", ")) # 출력: ['Hello', 'World!']
print(", ".join(["Hello", "World!"])) # 출력: Hello, World!
시작과 끝 검사
s = "Hello, World!"
print(s.startswith("Hello")) # 출력: True
print(s.endswith("!")) # 출력: True
문자열 형식화
포맷팅 (Formatting)
- % 연산자
name = "Alice"
age = 30
print("My name is %s and I am %d years old." % (name, age)) # 출력: My name is Alice and I am 30 years old.
- str.format() 메서드
name = "Alice"
age = 30
print("My name is {} and I am {} years old.".format(name, age)) # 출력: My name is Alice and I am 30 years old.
print("My name is {0} and I am {1} years old.".format(name, age)) # 출력: My name is Alice and I am 30 years old.
print("My name is {name} and I am {age} years old.".format(name=name, age=age)) # 출력: My name is Alice and I am 30 years old.
- f-string (Python 3.6 이상)
name = "Alice"
age = 30
print(f"My name is {name} and I am {age} years old.") # 출력: My name is Alice and I am 30 years old.
기타 유용한 메서드
문자열 검사
s = "Hello"
print(s.isalpha()) # 출력: True
s = "123"
print(s.isdigit()) # 출력: True
s = "Hello123"
print(s.isalnum()) # 출력: True
문자열 확장
s = "42"
print(s.zfill(5)) # 출력: 00042
s = "hello"
print(s.center(10, "-")) # 출력: --hello---
문자열 이스케이프 시퀀스
print("Hello\nWorld") # 출력: Hello
# World
print("Hello\tWorld") # 출력: Hello World
print("He said, \"Hello\"") # 출력: He said, "Hello"
이렇게 다양한 방법으로 Python에서 문자열을 다룰 수 있습니다. 각 방법은 상황에 따라 다르게 활용될 수 있으며, 문자열을 처리하고 조작하는 데 매우 유용합니다.
반응형
'언어 > Python' 카테고리의 다른 글
[ Python ] for문 사용하기 (1) | 2024.06.03 |
---|---|
[ Python ] 리스트 사용하기 (0) | 2024.06.03 |
[ Python ] 선행 참조 문제 다루기 (0) | 2024.06.03 |
[ Python ] 불리언 연산자 다루기 (1) | 2024.06.03 |
[ Python ] 야구게임 프로그램을 만들자. (0) | 2024.06.03 |