8 장문자열 박창이 서울시립대학교통계학과 박창이 ( 서울시립대학교통계학과 ) 8 장문자열 1 / 24
학습내용 문자열 (string) 훑기 (traversal) 부분추출 (slicing) print 함수불변성 (immutablity) 검색 (search) 세기 (count) Method in 연산자비교 박창이 ( 서울시립대학교통계학과 ) 8 장문자열 2 / 24
문자열 I 인덱스 >>> fruit = banana >>> letter = fruit[1] >>> print(letter) a >>> letter = fruit[0] >>> print(letter) b >>> letter = fruit[1.5] Traceback (most recent call last): File "<input>", line 1, in <module> TypeError: string indices must be integers 박창이 ( 서울시립대학교통계학과 ) 8 장문자열 3 / 24
문자열 II len 함수 >>> len(fruit) 6 >>> length = len(fruit) >>> last = fruit[length-1] >>> print(last) a >>> print(fruit[-1]) # last a >>> print(fruit[-2]) # last - 1 n 박창이 ( 서울시립대학교통계학과 ) 8 장문자열 4 / 24
문자열 III 특수문자 (escape sequence) >>> sentence = "He said, \"This parrot s dead.\"" >>> sentence He said, "This parrot\ s dead." >>> print(sentence) He said, "This parrot s dead." >>> subjects = Physics\nChemistry\nBiology >>> subjects Physics\nChemistry\nBiology >>> print(subjects) Physics Chemistry Biology 박창이 ( 서울시립대학교통계학과 ) 8 장문자열 5 / 24
문자열 IV >>> print("languages:\n\tpython\n\tc\n\tjavascript") Languages: Python C JavaScript 박창이 ( 서울시립대학교통계학과 ) 8 장문자열 6 / 24
훑기 I 문자열을훑어가며한글자씩출력 index = 0 while index < len(fruit): letter = fruit[index] print(letter) index = index + 1 # or for char in fruit: print(char) 박창이 ( 서울시립대학교통계학과 ) 8 장문자열 7 / 24
훑기 II 문자열합치기 (concatenation) >>> prefixes = JKLMNOPQ >>> suffix = ack >>> for letter in prefixes: print(letter + suffix) Jack Kack Lack Mack Nack Oack Pack Qack 박창이 ( 서울시립대학교통계학과 ) 8 장문자열 8 / 24
부분추출 >>> s = Monty Python >>> print(s[0:5]) Monty >>> print(s[6:12]) Python >>> fruit[:3] ban >>> fruit[3:] ana >>> fruit[3:3] 박창이 ( 서울시립대학교통계학과 ) 8 장문자열 9 / 24
print 함수 I >>> heading = Index of Dutch Tuplip Prices >>> line = + + - *16 + - *14 + + >>> print(line, heading, line, Nov 23 1636 100, Nov 25 1636 673, line, sep= \n ) +------------------------------+ Index of Dutch Tuplip Prices +------------------------------+ Nov 23 1636 100 Nov 25 1636 673 +------------------------------+ >>> import math >>> print("pi is %10.4f" % math.pi) Pi is 3.1416 박창이 ( 서울시립대학교통계학과 ) 8 장문자열 10 / 24
print 함수 II >>> print("pi is %2.7f" % math.pi) Pi is 3.1415927 # or >>> print("pi is {:10.4f}".format(math.pi)) Pi is 3.1416 >>> print("pi is {:2.7f}".format(math.pi)) Pi is 3.1415927 >>> St1="Hello my friend" >>> "{:s} : {:2.5f}".format(St1, math.pi) Hello my friend : 3.14159 >>> number = 10 >>> day = "three" >>> "I ate {0} apples. so I was sick for {1} days.".format(number, day) I ate 10 apples. so I was sick for three days. 박창이 ( 서울시립대학교통계학과 ) 8 장문자열 11 / 24
print 함수 III >>> "I ate {number} apples. so I was sick for {day} days.". format(number=10, day=3) I ate 10 apples. so I was sick for 3 days. >>> "{0:<10}".format("hi") hi >>> "{0:>10}".format("hi") hi >>> "{0:^10}".format("hi") hi >> "{0:=^10}".format("hi") ====hi==== 박창이 ( 서울시립대학교통계학과 ) 8 장문자열 12 / 24
불변성 기존의문자열은변경이불가능함. 즉불변임 >>> greeting = Hello, world! >>> greeting[0] = J Traceback (most recent call last): File "<pyshell#78>", line 1, in <module> greeting[0] = J TypeError: str object does not support item assignment >>> new_greeting = J + greeting[1:] >>> print(new_greeting) Jello, world! 박창이 ( 서울시립대학교통계학과 ) 8 장문자열 13 / 24
검색 주어진단어에서문자찾기 def find(word, letter): index = 0 while index < len(word): if word[index] == letter: return index index = index + 1 return -1 박창이 ( 서울시립대학교통계학과 ) 8 장문자열 14 / 24
세기 문자열에서단어 a 의출현횟수 word = banana count = 0 for letter in word: if letter == a : count = count + 1 print(count) 박창이 ( 서울시립대학교통계학과 ) 8 장문자열 15 / 24
문자열메소드 I 메소드 (method) 는함수와유사 >>> word = banana >>> new_word = word.upper() >>> print(new_word) BANANA >>> word.find( na ) 2 >>> word.find( na, 3) 4 >>> name = bob >>> name.find( b, 1, 2) -1 >>> a = java python c++ fortran >>> a.isalpha() False >>> b = a.title() 박창이 ( 서울시립대학교통계학과 ) 8 장문자열 16 / 24
문자열메소드 II >>> b Java Python C++ Fortran >>> c = b.replace(,!\n ) >>> c Java!\nPython!\nC++!\nFortran >>> print(c) Java! Python! C++! Fortran >>> c.index( Python ) 6 >>> St1 = "This is NICE" >>> St2 = "2017" >>> St3 = "WOW" >>> St4 = "Year 12345" >>> St1.isalnum() # all char s are numbers? 박창이 ( 서울시립대학교통계학과 ) 8 장문자열 17 / 24
문자열메소드 III False >>> St2.isdigit() # all digits True >>> St3.isupper() # all upper case? True >>> St4.endswith( 5 ) # ends with 5? True >>> a = "hobby" >>> a.count("b") 2 >>> ",".join("abcd") a,b,c,d >>> a = " hi " >>> a.lstrip() hi 박창이 ( 서울시립대학교통계학과 ) 8 장문자열 18 / 24
문자열메소드 IV >>> a.rstrip() hi >>> a.strip() hi >>> a = "Life is too short" >>> a.split() # blank [ Life, is, too, short ] >>> b = "a:b:c:d" >>> b.split(":") # : [ a, b, c, d ] 박창이 ( 서울시립대학교통계학과 ) 8 장문자열 19 / 24
in 연산자 두번째문자열에첫번째문자열이나타나면 True 없으면 False >>> a in banana True >>> seed in banana False >>> def in_both(word1, word2): for letter in word1: if letter in word2: print(letter) >>> in_both( apples, oranges ) a e s 박창이 ( 서울시립대학교통계학과 ) 8 장문자열 20 / 24
비교 Python 에서는대문자가소문자보다앞서나옴 if word == banana : print( All right, bananas. ) 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. ) 대소문자를피하기위해모두소문자로바꾼후에비교할수있음 박창이 ( 서울시립대학교통계학과 ) 8 장문자열 21 / 24
디버깅 I 문자열의순서가반대인지체크하는함수 >>> def is_reverse(word1, word2): if len(word1)!= len(word2): return False i = 0 j = len(word2) while j > 0: print(i, j) if word1[i]!= word2[j]: return False i = i + 1 j = j - 1 return True 박창이 ( 서울시립대학교통계학과 ) 8 장문자열 22 / 24
디버깅 II >>> is_reverse( pots, stop ) 0 4 Traceback (most recent call last): File "<pyshell#102>", line 1, in <module> is_reverse( pots, stop ) File "<pyshell#101>", line 10, in is_reverse if word1[i]!= word2[j]: IndexError: string index out of range 박창이 ( 서울시립대학교통계학과 ) 8 장문자열 23 / 24
디버깅 III j = len(word2) - 1 로수정하면바르게작동 >>> is_reverse( pots, stop ) 0 3 1 2 2 1 True 박창이 ( 서울시립대학교통계학과 ) 8 장문자열 24 / 24