Notice
Recent Posts
Recent Comments
Link
250x250
develope_kkyu
[Python] str 메서드 본문
728x90
str 메서드¶
- 파이썬 함수 (=Methods) 사용법 익히기
- 관련 문서 확인하기
- https://docs.python.org/3/library/stdtypes.html#string-methods
- 항목 추가
- 항목 추가
In [46]:
# Capitalize
text = 'i love YOU' # str 클래스 객체
print(type(text))
result = text.capitalize() # 첫 글자 대문자 만들어주는 메서드
result = text.capital() # 에러 : 관련된 함수가 없다.
print(result)
<class 'str'>
--------------------------------------------------------------------------- AttributeError Traceback (most recent call last) <ipython-input-46-0a6a21c00888> in <module> 3 print(type(text)) 4 result = text.capitalize() ----> 5 result = text.capital() # 에러 : 관련된 함수가 없다. 6 print(result) AttributeError: 'str' object has no attribute 'capital'
In [44]:
text = ' python is best '
print(text)
result = text.strip() # 양쪽 공백을 없애주는 메서드
#lstrip은 왼쪽 공백, rstrinp은 오른쪽 공백
print(result)
python is best python is best
In [57]:
# split
# 문장을 분리하는 메서드
text = "국내 연구팀이 벽과 천장을 빠르게 기어다니며 점검, 수리 등 위험한 작업을 대신해줄 수 있는 사족보행 로봇을 개발했다."
result = text.split(' ')
print(result)
print(type(result)) # 결과 : 리스트
['국내', '연구팀이', '벽과', '천장을', '빠르게', '기어다니며', '점검,', '수리', '등', '위험한', '작업을', '대신해줄', '수', '있는', '사족보행', '로봇을', '개발했다.'] <class 'list'>
In [61]:
# count
# 문자열 중 같은 문자의 개수를 보여주는 메서드
text = "text"
result = text.count("t")
print(result)
2
In [68]:
# find
# 처음 위치를 알려주는 메서드
text = "human"
result1 = text.find("m")
result2 = text.find("k")
print(result1)
print(result2) # 찾는 값이 존재 하지 않는다면 -1
2 -1
In [71]:
# index
# 처음 위치를 알려주는 메서드
text = "human"
result1 = text.index("m")
result2 = text.index("k")
print(result1)
print(result2) # 찾는 값이 존재 하지 않는다면 에러
--------------------------------------------------------------------------- ValueError Traceback (most recent call last) <ipython-input-71-ba67f9501537> in <module> 3 text = "human" 4 result1 = text.index("m") ----> 5 result2 = text.index("k") 6 print(result1) 7 print(result2) # 찾는 값이 존재 하지 않는다면 에러 ValueError: substring not found
In [74]:
# join
# 문자열 삽입 메서드
text = "human"
result = " ".join(text)
print(result)
h u m a n
In [76]:
# upper
# 소문자를 대문자로 바꾸는 메서드
text = "human"
result = text.upper()
print(result)
HUMAN
In [78]:
# lower
# 대문자를 소문자로 바꾸는 메서드
text = "HUMAN"
result = text.lower()
print(result)
human
In [81]:
# replace
# 문자열을 바꿔주는 메서드
text = "human is strong"
print(text)
result = text.replace("human", "gorila")
print(result)
human is strong gorila is strong
출처 : 휴먼교육센터, Evan 강사님
728x90
'Python' 카테고리의 다른 글
[Python] pandas 예제 - 1 (1) | 2022.12.30 |
---|---|
[Python] 튜플(tuple)과 리스트(list) 비교 (0) | 2022.12.26 |
[Python] List (0) | 2022.12.26 |
[Python] 파이썬 시작하기 - vs code (0) | 2022.12.23 |
[Python] 파이썬 시작하기 - Pycharm (0) | 2022.12.23 |