[파이썬 문법/문자열] 1. 문자열 메서드

김진만·2023년 1월 5일
0

파이썬 기초

목록 보기
1/1

1. upper(), lower()

각각 문자열을 대문자 , 소문자로 치환

sentence = "abc"
print(sentence.upper())
# > ABC

2. replace(old , new, count )

old 자리의 문자열을 new 문자열로 치환 count만큼

sentence = "abcabcabc"
print(sentence.replace('abc','def',1))
# 기대값: defabcabc ( 1회 치환 )

3. find() , count()

문자열의 인덱스(시작 위치) 찾을 때 / 개수 셀 때

sentence = 'this cat is super cat'
print(sentence.find('cat'))
=> 5
print(sentence.count('cat'))
=> 2

4. split()

문자열 분할

sentence = 'this cat is super cat'
print(sentence.split())  #1
print(sentence.split(' '))  #2 
print(sentence.split(' is '))  #3
#1->['this', 'cat', 'is', 'super', 'cat'] case1==case2
#2->['this', 'cat', 'is', 'super', 'cat'] case2==case1
#3->['this cat', 'super cat']  is 앞뒤로 공백 주의!

5. join()

문자열, 리스트 합체! 구분자를 인자로

sentence = 'this cat is super cat'
print(''.join(sentence)) #1
for i in ''.join(sentence): #2
    print(i,end=' ')
print('')
#1->this cat is super cat
#2->t h i s   c a t   i s   s u p e r   c a t
new_sentence = sentence.split()
print(new_sentence) #3
print(' '.join(new_sentence)) #4
print(type(' '.join(new_sentence))) #5
#3->['this', 'cat', 'is', 'super', 'cat']
#4->this cat is super cat
#5-> <class 'str'>

6. lstrip(),rstrip(),strip()

좌 공백제거, 우 공백제거, 앞뒤 공백제거

sentence = '   this cat is super cat   '
print(sentence)
print(sentence.lstrip())
print(sentence.rstrip())
print(sentence.strip())
#1->   this cat is super cat   
#2->this cat is super cat   
#3->   this cat is super cat
#4->this cat is super cat
profile
충분한 전기와 컴퓨터 한 대와 내 이 몸만 남아 있다면 지구를 재건할 수 있습니다.

0개의 댓글