반응형

5. 문자열(String) 관련 함수, 메소드

 

 

문자열 관련 함수, 메소드

 

 

문자열 자료형은 자체적으로 가지고 있는 내장 함수들이 있다. 

내장함수를 사용하려면 문자열 변수 이름 뒤에 마침표('.')를 붙인 다음에 함수 이름을 써주면 된다.

 

사용 예 :

 

A = "MARU"

B = A.count("M")

 

 

문자 개수 세기

- 지정한 문자가 갯수 반환

count

a = "address"

print(a.count('d'))

2

위치 알려주기1

- 지정한 문자의 인덱스 반환

- 없을 시 -1 반환

find

a = "Python is good language"

print(a.find('g'))

print(a.find('m'))

10
-1

위치 알려주기2

- 지정한 문자의 인덱스 반환

- 없을 시 error

index

a = "You are very good man"
print(a.index('g'))
print(a.index('k'))
13
Traceback (most recent call last):
  File "C:\JBMPA\lecture\test.py", line 6, in <module>
    print(a.index('k'))
ValueError: substring not found

문자열 삽입

- join 함수안의 문자나 배열을 분리하여

join 앞의 문자와 연결 시켜줌

join

print(",".join('abcd'))

print(",".join(['a', 'b', 'c', 'd']))

a,b,c,d

a,b,c,d

소문자를 대문자로 바꾸기

upper

a = "hi"

print(a.upper())

HI

대문자를 소문자로 바꾸기

lower

a = "HI"

print(a.lower())

hi

양쪽 공백 지우기

strip

a = " hi "

print(a.strip())

'hi'

왼쪽 공백 지우기

lstrip

a = " hi "

print(a.lstrip())

'hi '

오른쪽 공백 지우기

rstrip

a = " hi "

print(a.rstrip())

' hi'

문자열 바꾸기(replace)

replace

a = "You are very good man"

print(a.replace("good", "bad"))

Your are very bad man

문자열 나누기(split)

- 지정한 문자를 기준으로 문자열을

나누어서 List로 반환

split

a = "You are very good man"

print(a.split(" "))

a = "a:b:c:d"

print(a.split(':'))

['You', 'are', 'very', 'good', 'man']
['a', 'b', 'c', 'd']

 

 

 

 

 

+ Recent posts