문자열에 적용되는 메서드

String Methods

(1) capitalize() /upper()
(2) count()
(3) startswith() /endswith()
(4) strip()

(1) capitalize() /upper()

capitalize() : Converts the first character to upper case
🍟 문자열의 맨 앞글자를 대문자로 바꾼다.
upper() : Converts a string into upper case
🍟 문자열의 모든 글자를 대문자로 바꾼다.

Example

x = 'hi. juri'
x.capitalize() #'Hi, juri'
x.upper() #'HI, JURI'

(2) count()

count() : Returns the number of times a specified value occurs in a string
🍟 지정한 값이 문자열 내에서 몇 번 등장하는지 반환한다.

Example

x = 'banana'
x.count('n') #2

(3) startswith() /endswith()

startswith() : Returns true if the string starts with the specified value
endswith() : Returns true if the string ends with the specified value
🍟 문자열이 특정 값으로 시작/끝나면 true를 반환한다.

Example

x = 'Hi, juri'
x.startswith('Hi') #True
x.endswith('Hi') #False
  • if문에서 자체로 조건이 될 수 있다.

(4) strip()

strip() : Returns a trimmed version of the string
🍟 문자열의 처음과 끝에 있는 지정한 문자를 제거한다.

Example

line = ',,,,i am juri....'
line.strip(',.') #'i am juri'

🍩연습) txt문서 가공하기


(1) 번호 사이에 있는 숫자제거
(2) 번호 뒤에 있는 온점제거

1차 코드

f = open('number.txt', 'r')
for line in f :
    a = line.strip('.')
    if not a.startswith('010') :
        continue
    print(a)

결과

010-1234-5000.

010-1234-5001.

010-1234-5002.

010-1234-5003.

🍕 Review

  • 알 수없는 줄공백 등장
  • 온점 제거 안됐음 / 중간숫자 제거 됐음

2차코드

f = open('number.txt', 'r')
for line in f :
    a = line.strip()
    b = a.strip('.')
    if not b.startswith('010') :
        continue
    print(b)

👉 수정 : line.strip()으로 줄공백 제거

결과

010-1234-5000
010-1234-5001
010-1234-5002
010-1234-5003

🍕 Review

  • success!
  • 줄공백은 txt파일의 Enter때문에 등장하는 현상
  • if문의 continue는 루프 맨 처음으로 돌아간다
    <코드 흐름>
    제거할숫자 -> if not b.starswith('010') -> true -> continue -> print되지않고 루프 처음으로 돌아감
    010-숫자-숫자 -> if not b.startswith('010') -> False -> print되고 루프 처음으로 돌아감
profile
Make my day !

0개의 댓글

관련 채용 정보

Powered by GraphCDN, the GraphQL CDN