오늘은 문자열에 대해 알아보자
s = 'hello'
print(len(s))

s = 'hello'
print(s[0])
print(s[::-1]) # 문자열 역순 나열

a= 'hello'
b = a.index('l')
c = a.rindex('l')
print(b)
print(c)
>> 왼쪽부터 찾는것와 오른쪽부터 찾는 인덱스 위치가 다르다!

s = 'hello, my name is alice'
s_find = s.find('b')
print(s_find)

s = 'hello, my name is alice'
s_fin = s.rfind('a')
print(s_fin)

📌 검색 구간 지정 가능
s = 'hello, my name is alice'
s_fin = s.rfind('a',0, 7) #인덱스 0에서 6까지 검색
print(s_fin)

s = 'hello, my name is alice'
print(s[0:-2]) #0부터 -3 인덱스까지 추출

#lstrip() 왼쪽부터 "문자조합"의 모든 문자 제거
s = "가hello나"
s_strip = s.lstrip("가h나")
print(s_strip)
#rstip() 오른쪽부터 "문자조합"의 모든 문자 제거
s = "가hello나"
s_strip = s.rstrip("가h나")
print(s_strip)


s = "뜨거운 아메리카노"
s_re = s.replace("뜨거운", "차가운")
print(s_re)

대문자 변환 case_text = text.upper()
소문자 변환 case_text = text.lower()
s1 = 'helle world'
s1_up = s1.upper()
s2 = 'HELLO WORLD'
s2_low = s2.lower()
print(s1_up)
print(s2_low)

s = 'helle hello'
s_c = s.count('h')
print(s_c)

| 함수 | 설명 | 예제 |
|---|---|---|
isdigit() | 문자열이 모두 숫자인지 여부를 확인 | "123".isdigit() → True |
isalpha() | 문자열이 모두 알파벳 문자인지 여부를 확인 | "abc".isalpha() → True |
isalnum() | 문자열이 모두 알파벳 문자 또는 숫자로만 구성되어 있는지 여부를 확인 | "abc123".isalnum() → True |
isspace() | 문자열이 모두 공백 문자 (space, tab, newline 등)로만 구성되어 있는지 여부를 확인 | " ".isspace() → True |
isnumeric() | 문자열이 수치형인지 여부를 확인 | "123".isnumeric() → True |
isdecimal() | 문자열이 십진수인지 여부를 확인 | "123".isdecimal() → True |
python3부터는 한글도 알파벳으로 인식
ex) "ㅠㅠ".isalpha() True 출력
s = '우리나라'
s_find = s.find('나')
if s_find != -1 :
print('"나"가 포함되어 있습니다', s_find)
else:
print('"나"가 포함되어 있지 않습니다')

s = input("세 개 이상 단어로 구성된 문자열을 입력하세요: ")
new_s = s.strip() #양쪽 끝 공백 제거
index_s = new_s.find(' ') #첫번째-두번째 단어 사이 공백 찾기
new_s = new_s[index_s+1:].strip() #단어 사이 공백 제거
print("단어 사이 공백 제거: ", new_s)
index_s = new_s.find(' ')
print("두번째 단어: ", new_s[:index_s])

s= "Hello World"
s_strip = s.strip()
indexing_s = s_strip.find(' ')
new_s = s_strip[indexing_s +1: ]
indexing_s = new_s.find("o")
print('두번째 "o" 인덱스: ', indexing_s)

#1 replace사용
s = input('".jpg"로 끝나는 파일 이름을 입력하세요:')
new_s = s.replace('.jpg', '.png')
print(new_s)
#2 replace 사용하지 않음
s = input('".jpg"로 끝나는 파일 이름을 입력하세요:')
new_s = s[:-3] + 'png' # 0부터 -4인덱스 + png
print(new_s)

s = "Beautiful.image.png"
find_s = s.rfind('.')
new_s = s[:find_s]
print(new_s)

s1 = input("첫번째 문자열을 입력하세요: ")
s2 = input("두번째 문자열을 입력하세요: ")
if s1.find(s2) != -1:
indexing_s2 = s1.find(s2)
print("두번째 문자열이 첫번째 문자열에서 시작하는 인덱스: ",indexing_s2)
else:
print("두번째 문자열이 첫번째 문자열에 존재하지 않습니다!")
