Language/Python

[Python] string 자료형

Junhong Kim 2019. 1. 7. 23:22
728x90
반응형


count()

문자 개수 세기

s = 'Life is too short, You need Python'
print(s.count('o'))
# 5


find()
문자열에서 특정 문자 또는 문자열이 처음 나오는 인덱스를 반환합니다.

만약, 찾는 문자나 문자열이 존재하지 않을 경우 -1을 반환합니다.

s = 'Life is too short, You need Python'
print(s.find('o'))
# 9
print(s.find('x'))
# -1


rfind()

뒤에서 부터 시작해서 문자 또는 문자열이 처음 나오는 인덱스를 반환합니다.

s = 'Life is too short, You need Python'
print(s.rfind('o'))
# 32


index()

문자열에서 특정 문자 또는 문자열이 처음 나오는 인덱스를 반환합니다.

만약, 찾는 문자나 문자열이 존재하지 않을 경우 ValueError 에러를 반환합니다.

s = 'Life is too short, You need Python'
print(s.index('o'))
# 9
print(s.index('x'))
# Traceback (most recent call last):
#   File "exp-string-method.py", line 2, in <module>
#     print(s.index('x'))
# ValueError: substring not found


join()

문자열의 각 문자에 특정 문자를 삽입하여 합칩니다.

s = 'Python'
print(','.join(s))
# P,y,t,h,o,n


split()

문자열을 특정 문자로 분할합니다.

split()에 인자가 없을 경우 공백(스페이스, 탭, 엔터 등)을 기준으로 문자열을 나눕니다.

s = 'Life is too short, You need Python'
print(s.split())
# ['Life', 'is', 'too', 'short', 'You', 'need', 'Python']

s = 'a,b,c,d'
print(s.split(','))
# ['a', 'b', 'c', 'd']


upper()

문자열을 모두 대문자로 바꿉니다.

s = 'Life is too short, You need Python'
print(s.upper())
# LIFE IS TOO SHORT, YOU NEED PYTHON


lower()

문자열을 모두 소문자로 바꿉니다.

s = 'Life is too short, You need Python'
print(s.lower())
# life is too short, you need python


lstrip()

왼쪽 공백 지우기

s = ' Python '
print(s.lstrip())
# 'Python'


rstrip()

오른쪽 공백 지우기

s = ' Python '
print(s.rstrip())
# ' Python'


strip()

양쪽 공백 지우기

s = ' Python '
print(s.strip())
# 'Python'


replace()

특정 문자열을 다른 문자열로 바꿉니다.

s = 'Python'
print(s.replace('P', 'Cp'))
# Cpython

References

https://wikidocs.net/13#_16

https://stackoverflow.com/questions/9572490/find-index-of-last-occurrence-of-a-substring-in-a-string

728x90
반응형