-
[Python] 1-2 문자열을 다루는 다양한 방법들05. Programing Language/[Python] 1. 파이썬 자료구조 2020. 1. 8. 21:54
far 오늘은 배울 게 많네요
호흡을 깊이 들이마시고!
들어갑니다
1. 문자열 슬라이싱
문자열: M o n t y P y t h o n
인덱스: 0 1 2 3 4 5 6 7 8 9 10 11
s = 'Monty Python' print(s[0:4]) #결과: Mont print(s[6:7]) #P print(s[6:20]) #Python
-문자열을 쪼개서 가져옵니다.
-s[0:4] 의미는 0번 인덱스에서부터 4번 인덱스까지인데
두 번째 숫자는 ~까지 이지만 포함하지는 않는다.
다시 말해 실제 출력되는 숫자는 0번 인덱스에서 3번 인덱스 까지라는 말이다.
-두 번째 숫자가 마지막 인덱스 너머를 가리키는 경우 문자열의 마지막에서 멈춘다.
예제에서 s[6:20] 이 그와 같은 경우이다.
s = 'Monty Python' print(s[:2]) #Mo print(s[8:]) #thon print(s[:]) #Monty Python
-첫 번째 숫자를 적지 않을 경우 문자의 시작으로 가정
-두 번째 숫자를 적지 않을 경우 문자의 마지막으로 가정
-그렇다.
2. 논리 연산자로서의 in
fruit = 'banana' 'n' in fruit #True 'm' in fruit #Fasle 'nan' in fruit #True if 'a' in fruit : print('Fount it!') #Found it!
-in 키워드는 어떤 문자열이 다른 문자열에 "포함"되는지
확인하기 위해서도 사용된다.
-in 표현식은 참 또는 거짓 값을 반환하는 논리 표현식이며 if 구문에
사용될 수 있다.
3. 문자열 비교
word = 'Banana' if word < 'banana': print('Your word,' + word + ', comes before banana.') elif word > 'banana': print('Your word,' + word + ', comes after banana.') else: print('All right, bananas.') #저는 before로 나오네요
-사전 순서상 앞인지 뒤인지 비교할 수 있다.
-일반적으로 대문자가 소문자보다 순서가 작다. 즉 빠르다(각자
피씨의 문자 설정마다 다를 수 있다. 직접 해서 알아봐야 한다. )
4. 문자열 라이브러리
greet = 'Hello Bob' zap = greet.lower() #.upper()는 대문자로변환. print(zap) #hello bob print(greet) #Hello Bob (원래 변수에는 영향을 미치지 않는다) print('Hi There'.lower()) #요렇게도 되네요 #hi there
-자바랑 비슷하네요.
stuff = 'Hello world' type(stuff) #<class 'str'> 말그대로 타입, 클래스를 알려주네요 dir(stuff) #['capitalize','casefold',......,'zfill'] 길어서 다 못적었습니다 #내장된 메소드들 또는 문자열로 할 수 있는 것 을보여줍니다.
https://docs.python.org/3/library/stdtypes.html#string-methods
(string 관련 메소드에 관한 문서입니다.)
이 중 제가 자주 사용하는 메소드를 몇 개 살펴보겠습니다.
4-1 문자열 탐색
fruit = 'banana' pos = fruit.find('na') print(pos) #2 aa = fruit.find('z') print(aa) #-1
-find 하위 문자열의 첫 번째로 나타나는 위치를 검색합니다.
-하위 문자열을 찾지 못하면 -1
4-2 찾아서 바꾸기
매우 매우 유용한 기능입니다.
greet = 'Hello Bob' nstr = greet.replace('Bob', 'Jane') print(nstr) #Hello Jane nstr = greet.replace('o','X') print(nstr) #HellX BXb
-역시 원본은 바뀌지 않습니다.
4-3 공백 제거
greet = ' Hello Bob ' greet.lstrip() #'Hello Bob ' greet.rstrip() #' Hello Bob' greet.strip() #'Hello Bob'
-제 구독자 들은 모두 쉽게 이해하실 거라고 생각됩니다.
-l은 left이고, r은 right의 약자입니다.
-중간의 공백은 안 없어지네요.
4-4 접두사
line = 'Please have a nice day' line.startswith('Please') #True line.startswith('p') #False
-문자열은 'Please'로 시작하나요? True
-문자열은 소문자'p'로 시작하나요? False
5. 파싱과 추출
From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008
메일함에서 가져온 이메일 폼이다. 앞으로 자주 보게 될 듯싶다.
data = 'From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008' atpos = data.find('@') print(atpos) #21 sppos = data.find(' ',atpos)# atpos 위치에서 시작 해서 공백 이나올때까지 탐색! print(sppos) #31 host = data[atpos+1 : sppos] print(host) #uct.ac.za
- ~까지이지만 포함하지 않는다는 것의 장점을 확인해 볼 수 있었다.
6. 두 종류의 문자열
파이썬 3에서는 모든 문자열이 유니코드이다.
파이썬 2에서는 조금 혼동이 있었다.
#Python 3 x = '이광춘' type(x) #<class 'str'> x = u'이광춘' type(x) #<class 'str'> #파이썬2는 <type 'unicode'>로 출력된다.
'05. Programing Language > [Python] 1. 파이썬 자료구조' 카테고리의 다른 글
[Python] 2-3 <실습> 파일 열고 읽기 (0) 2020.01.13 [Python] 2-2 파일 읽기 (0) 2020.01.13 [Python] 2-1 파일 열기 (0) 2020.01.13 [Python] 1-3 <실습> 문자열 파싱 (0) 2020.01.09 [Python] 1-1 문자열 (0) 2020.01.08