s = "Hello"
reversed_s = s[::-1]
print(reversed_s) # "olleH"
s = "Hello"
reversed_s = ''.join(reversed(s))
print(reversed_s) # "olleH"
s = "Hello"
reversed_s = ""
for char in s:
reversed_s = char + reversed_s
print(reversed_s) # "olleH"
s = 'banana'
first_index = s.index('a') # 첫 번째 'a': 1
second_index = s.index('a', first_index + 1) # 두 번째 'a': 3
print(second_index) # 3
s = 'banana'
first_index = s.find('a') # 첫 번째 'a': 1
second_index = s.find('a', first_index + 1) # 두 번째 'a': 3
print(second_index) # 3
s = 'banana'
last_index = s.rfind('a') # 마지막 'a': 5
print(last_index) # 5
s = 'banana'
last_index = s.rindex('a') # 마지막 'a': 5
print(last_index) # 5
strip() 메서드문자열의 앞뒤 공백(또는 지정한 문자)을 제거하는 함수입니다. 새로운 문자열을 반환하며 원본은 바뀌지 않습니다.
s = " hello "
print(s.strip()) # "hello" (앞뒤 공백 제거)
s = "***hello***"
print(s.strip("*")) # "hello" (앞뒤 * 제거)
변형:
lstrip(): 왼쪽(앞)만 제거rstrip(): 오른쪽(뒤)만 제거isspace() 메서드문자열이 공백 문자로만 구성되어 있는지 확인하고, True/False를 반환하는 판별 함수입니다.
print(" ".isspace()) # True (공백만 있음)
print("\t".isspace()) # True (탭도 공백으로 인식)
print(" hello".isspace()) # False (공백 + 문자)
print("".isspace()) # False (빈 문자열은 아님)
공백 문자 범위:
)\t)\n)\r)\f)\v)s1 = " "
s2 = " hello "
print(s1.isspace()) # True: 공백만으로 구성
print(s2.isspace()) # False: 공백 + 문자
print(s1.strip()) # "": 공백 제거 후 빈 문자열
print(s2.strip()) # "hello": 공백 제거 후 문자만 남음
요약:
strip() → 공백 제거 (문자열 반환)isspace() → 공백 여부 판별 (True/False 반환)new_str = old_str.replace(찾을문자, 바꿀문자, [횟수])
찾을문자: 변경하고 싶은 대상
바꿀문자: 새로 대체할 내용
횟수(선택): 앞에서부터 몇 개만 바꿀지 지정 (생략 시 모두 변경).
text = "hello world, hello python"
# 1. 모든 'hello'를 'hi'로 변경
new_text = text.replace("hello", "hi")
print(new_text) # "hi world, hi python"
# 2. 앞에 있는 1개의 'hello'만 'hi'로 변경
one_change = text.replace("hello", "hi", 1)
print(one_change) # "hi world, hello python"
# 3. 공백 삭제 (자주 사용하는 팁)
no_space = text.replace(" ", "")
print(no_space) # "helloworld,hellopython"
문자열[시작:끝:간격]
시작(start): 잘라낼 시작 위치 (포함)
끝(end): 잘라낼 끝 위치 (미포함, 이 앞까지만 자름)
간격(step): 몇 칸씩 건너뛸지 설정 (생략 시 1).
text = "Hello Python"
print(text[0:5]) # "Hello" (0번부터 4번까지)
print(text[6:12]) # "Python" (6번부터 11번까지)
print(text[:5]) # "Hello" (처음부터 4번까지)
print(text[6:]) # "Python" (6번부터 끝까지)
print(text[:]) # "Hello Python" (전체 복사)
print(text[-6:]) # "Python" (뒤에서 6번째부터 끝까지)
print(text[::2]) # "HloPto" (2칸씩 건너뛰며 추출)
print(text[::-1]) # "nohtyP olleH" (거꾸로 뒤집기)