python/기타
python str(문자열) 함수 사용하기
Memory!
2022. 3. 28. 00:54
728x90
반응형
문자열 타입의 내장많이 사용하는 내장 함수
개발환경 : jupyter lab
1. 문자열 길이 구하기 : len()
str1 = "word"
len(str1)
2. 문자열 인덱싱, 문자열 자르기 : []
# 5번째 위치한 문자
str_index = "show me the money!"
str_index[5]
'm'
0 | 1 | 2 | 3 | 4 | 5 |
s | h | o | w | m |
# 문자열의 마지막에 위치한 문자
# -1은 뒤에서 1번째 -2는 뒤에서 2번째라고 생각하면 됨
str_index[-1], str_index[-2]
('!', 'y')
-6 | -5 | -4 | -3 | -2 | -1 |
m | o | n | e | y | ! |
범위를 지정해서 가져올수 있습니다.
ex) 0번째 ~ 3번째, 뒤에서 4번째 부터 끝까지 등
# 문자열 0번째 ~ 4번째
str_index[0:4]
'show'
# 뒤에서 4번째 부터 끝까지
str_index[-4:]
'ney!'
# 뒤에서 4번째 부터 끝에서 1개 빼고
print(str_index[-4:-1])
# 뒤에서 4번째 부터 끝에서 2개 빼고
print(str_index[-4:-2])
ney
ne
※ 문자열 범위를 지정하여 indexing 하는경우 -(음수) 사용하는 경우 유의 해서 사용하세요!
3. 문자열에 삽입하기 : join()
str_python = "python"
".".join(str_python)
'p.y.t.h.o.n'
"+-".join(str_python)
'p+-y+-t+-h+-o+-n'
4. 모두 대문자로, 모두 소문자로 : upper(), lower()
str_python = "Python1"
str_python.upper()
'PYTHON1'
숫자는 무시되고 알파벳만 적용 됩니다.
str_python = "PythoN1"
str_python.lower()
'python1'
5. 공백 지우기 : 양쪽 공백 지우기(strip) / 왼쪽 공백 지우기(lstrip) / 오른쪽 공백 지우기(rstrip)
a = " hi "
a.strip()
'hi'
a.lstrip()
'hi '
a.rstrip()
' hi'
6. 문자 변경하기 : replace()
str_index = "show me the money!"
str_index.replace('!', '#')
'show me the money#'
str_index = "show me the money!"
str_index.replace('money', 'passion')
'show me the passion!'
7. 문자열 나누기 : split()
# 공백을 기준으로 문자열을 나누기
str_index = "show me the money!"
str_index.split(" ")
['show', 'me', 'the', 'money!']
split을 하면 list 형태로 결과가 return 됩니다.
# 공백 기준으로 나눴을 때 첫번째로 나눠진 문자 가져오기
str_index.split(" ")[0]
'show'
문자열 함수의 경우 많이 쓰는 함수는 len(), replace(), 인덱싱, split() 입니다.
자주 쓰는 문자열 함수는 익숙해져아 코딩속도 및 실수를 하지 않게 되므로 많은 연습이 필요합니다.
728x90
반응형