Python

[Python] split(), strip(), find(), startswith(), endswith(), replace(), isalnum(), isspace() 함수

챈박 2021. 7. 27. 13:24

split() - 문자열 나누기

coffee_menu_str = "에스프레소, 아메리카노, 카페라테, 카푸치노"
coffee_menu_str.split(',')

-> ['에스프레소', ' 아메리카노', ' 카페라테', ' 카푸치노']
" 에스프레소 \n\n 아메리카노 \n 카페라테 카푸치노 \n\n".split()

-> ['에스프레소', '아메리카노', '카페라테', '카푸치노']
"에스프레소 아메리카노 카페라테 카푸치노 말차프라페".split(maxsplit=2)

-> ['에스프레소', '아메리카노', '카페라테 카푸치노 말차프라페']
phone_number = "+82-01-2345-6789" #국가 번호가 포함된 전화번호
split_num = phone_number.split("-", 1) #국가 번호와 나머지 번호 분리

print(split_num)
print("국내전화번호: {0}".format(split_num[1]))

->['+82', '01-2345-6789']
국내전화번호: 01-2345-6789

 


strip() - 문자열 앞뒤의 해당 문자 제거 (주의 : 앞뒤만)

test_str = "aaabbPythonbbbaa"
temp1 = test_str.strip('a') # 문자열 앞뒤의 'a' 제거
temp1

->'bbPythonbbb'

temp1.strip('b')

-> 'Python'
test_str_multi = "##***!!!##.... Python is powerful.!... %%!#..   "
test_str_multi.strip('*.#! %')

-> 'Python is powerful'
"\n This is very \n fast. \n\n".strip()

-> 'This is very \n fast.'

 


split(), strip() 활용

coffee_menu = " 에스프레소, 아메리카노,    카페라테   ,   카푸치노   "
coffee_menu_list = coffee_menu.split(',')

coffee_list = [] # 빈 리스트 생성
for coffee in coffee_menu_list:
    temp = coffee.strip() # 문자열의 공백 제거
    coffee_list.append(temp) # 리스트 변수에 추가
print(coffee_list) # 최종 리스트 출력

-> ['에스프레소', '아메리카노', '카페라테', '카푸치노']

 


find() - 문자열 찾기

tr_f = "Python code."

print("찾는 문자열의 위치:", str_f.find("Python"))
print("찾는 문자열의 위치:", str_f.find("code"))
print("찾는 문자열의 위치:", str_f.find("n"))
print("찾는 문자열의 위치:", str_f.find("easy")) #easy라는 문자열 존재 하지 않음 -> -1 반환

->
찾는 문자열의 위치: 0
찾는 문자열의 위치: 7
찾는 문자열의 위치: 5
찾는 문자열의 위치: -1
str_f_se = "Python is powerful, Python is easy to learn."

print(str_f_se.find("Python", 10, 30)) #시작 위치(start)와 끝 위치(end) 지정
print(str_f_se.find("Python", 35)) #찾기 위한 시작 위치(start) 지정

->
20
-1

 


startswith(), endswith() - 시작과 끝의 문자열이 해당 문자열인지 확인

str_se = "Python is pwerful, Python is easy to learn."

print("Python으로 시작?:", str_se.startswith("Python"))
print("is로 시작?:", str_se.startswith("is"))
print(".로 끝?:", str_se.endswith("."))
print("learn으로 끝?:", str_se.endswith("learn"))

->
Python으로 시작?: True
is로 시작?: False
.로 끝?: True
learn으로 끝?: False

 

 

 


replace() -  문자열 대체하기

str_a = 'Python is fast. Python is friendly. Python is open.'
print(str_a.replace('Python', 'IPython'))
print(str_a.replace('Python', 'IPython', 2))

->
IPython is fast. IPython is friendly. IPython is open.
IPython is fast. IPython is friendly. Python is open.

 

 


isalnum(), isspace()

print('acb1234'.isalnum()) #특수 문자나 공백이 아닌 문자와 숫자로 구성됨
print('    acb1234'.isalnum()) #문자열에 공백이 있음
print('    '.isspace()) #문자열이 공백으로만 구성됨
print('  1  '.isspace()) #문자열에 공백 외에 다른 문자가 있음

->
True
False
True
False

 

 

 

반응형