본문 바로가기
Python

[Python] 문자열 내장함수

by 기리의 개발로그 2023. 12. 27.

문자열 내장함수

파이썬 문자열 내장함수로는 count, find, index, join, upper, lower, lstrip, rstrip, strip, replace, split 가 있다.


count - 문자 갯수 세기


count(str)

  • str 문자(열)의 개수를 반환한다.
a = 'hobby'
print(a.count('b'))
2

find - 문자 위치 찾기(1)


find(str)

  • str 문자(열)의 인덱스를 반환한다.
  • str 문자(열)이 여러 개인 경우 가장 낮은 인덱스를 반환한다.
  • 찾지 못할 경우 -1을 반환한다.
a = "Python is the best choice"
print(a.find('P'))
print(a.find('T'))
0
-1

index - 문자 위치 찾기(2)


index(str)

  • str 문자(열)의 인덱스를 반환한다.
  • str 문자(열)이 여러 개인 경우 가장 낮은 인덱스를 반환한다.
  • 찾지 못할 경우 ValueError를 발생한다.
a = "Python is the best choice"
print(a.index('P'))

print(a.index('k'))
0

 Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
 ValueError: substring not found

join - 문자열 삽입


str.join(iterable)

  • iterable 문자(열)에 str을 삽입한 문자열을 출력한다.
  • iterable에는 문자열로 이루어진 리스트/튜플이나, 단순 문자열 입력이 가능하다.
print(",".join('abcd'))
print(",".join(['a', 'b', 'c', 'd']))
'a,b,c,d'
'a,b,c,d'

upper, lower - 대/소문자 변경


upper()

  • 문자(열)을 대문자로 변환한다.
a = 'hi'
print(a.upper())
'HI'


lower()

  • 문자(열)을 소문자로 변환한다.
b = 'HI'
print(b.lower())
'hi'

lstrip, rstrip, strip - 공백지우기


lstrip()

  • 문자열에서 가장 왼쪽에 있는 한 칸 이상의 연속된 공백들을 지운다.
a = " hi "
print(a.lstrip())
'hi '


rstrip()

  • 문자열에서 가장 오른쪽에 있는 한 칸 이상의 연속된 공백들을 지운다.
a = " hi "
print(a.rstrip())
' hi'


strip()

  • 문자열에서 양쪽에 있는 한 칸 이상의 연속된 공백들을 지운다.
a = " hi "
print(a.strip())
'hi'

replace - 문자열 바꾸기


replace(old, new)

  • old를 new로 바꿔준다.
a = "Life is too short"
print(a.replace("Life", "Your leg"))
'Your leg is too short'

split - 문자열 나누기


str.split([sep])

  • sep에 입력된 문자(열)을 이용하여 str 문자열을 분리시킨 후 리스트로 출력한다.
  • sep을 입력하지 않으면 공백을 기준으로 한다.
a = "Python is very goood"
print(a.split()) 

a='y:s:g'
print(a.split(':'))
['Python', 'is', 'very', 'goood']

['y', 's', 'g']
반응형

'Python' 카테고리의 다른 글

[Python] 인덱싱 / 슬라이싱  (26) 2023.12.29
[Python] 리스트  (31) 2023.12.28
[Python] 문자열 포맷팅  (45) 2023.12.26
[Python] 문자열  (36) 2023.12.22
[Python] 연산자  (23) 2023.12.21

댓글