728x90
반응형
1. 문자 개수 세기 (Count)
a="hobby"
print(a.count('b'))
#count()함수 사용 -> 문자열 중 문자 'b' 개수 출력
'2'
위치 알려주기 (fint, index)
a="Python is the best choice"
print(a.find('b'))
#b의 위치
print(a.find('k'))
#k 위치
14
#문자열에서 b가 처음 나온 위치
-1
#문자열에 존재하지 않을 때 -1이 반환됨
a="Life is too short"
print(a.index('t'))
print(a.index('k'))
8
#t가 처음 나온 위치
Traceback (most recent call last):
File "/Users/soheepark/Documents/a=1.py", line 3, in <module>
print(a.index('k'))
ValueError: substring not found
#k는 문자열에 없으므로 error가 남
문자열 삽입
print(",".join('abcd'))
#print(",".join(['a','b','c','d'])
#abcd 문자열 사이에 , 삽입
'a,b,c,d'
소문자 → 대문자 (upper)
a="hi"
print(a.upper())
'HI'
대문자 → 소문자 (lower)
a="HI"
print(a.lower())
#print(a.lower) : <built-in method lower...(생략) / 결과가 나오지 않는다. ()이 필요한가보다.
hi
왼쪽 공백 지우기 (lstrip)
a=" hi"
print(a.lstrip())
#원래는 " hi" 이렇게 출력이 되어야 한다.
hi
#왼쪽 공백 없이 출력이 되었다.
오른쪽 공백 지우기 (rstrip)
a=" hi "
print(a.rstrip())
' hi'
양쪽 공백 지우기 (strip)
a=" hi "
print(a.strip())
'hi'
문자열 바꾸기 (replace)
a="Life is too short"
print(a.replace("Life", "Your leg"))
#원래는 'Life is too short"로 출력이 되어야 함
#Life → Your leg
'Your leg is too short'
문자열 나누기 (split)
a="Life is too short"
print(a.split())
b="a:b:c:d"
print(b.split(':'))
#':'기준으로 문자열 나누기
'['Life', 'is', 'too', 'short']'
# a 출력 결과
'['a', 'b', 'c', 'd']'
# b 출력 결과
728x90
반응형
'[Language] > Python' 카테고리의 다른 글
[Jupyter Notebook] Index 제거 후 CSV 파일 저장 (0) | 2022.07.28 |
---|---|
Pip LightGBM : OSError (0) | 2022.07.26 |
문자열 입력(2) (1) | 2022.03.07 |
문자열 입력(1) (0) | 2022.03.06 |
연산자 (0) | 2022.03.06 |