s = 'abcdef' L = [100,200,300] t = ('tuple', 'object', 1, 2) s = 'abcdef' l = [100,200,300] print s[0] print s[1] print s[-1] print print l[1] l[1] = 900 print l[1] print l[100] s = 'abcdef' L = [100, 200, 300] print s[1:3] print s[1:] print s[:] print s[-100:100] print print L[:-1] # L[:2] 와 동일 print L[:2] s = 'abcd' print s[::2] #step:2 - 오른쪽 방향으로 2칸씩 print s[::-1] #step:-1 - 왼쪽 방향으로 1칸씩 s = 'abc' + 'def' print s L = [1,2,3] + [4,5,6] print L s = 'Abc' print s * 4 L = [1,2,3] print L * 2 s = 'abcde' print 'c' in s t = (1,2,3,4,5) print 2 in t print 10 in t print 10 not in t print 'ab' in 'abcd' print 'ad' in 'abcd' print ' ' in 'abcd' print ' ' in 'abcd ' s = 'abcde' l = [1,2,3] t = (1, 2, 3, 4) print len(s) print len(l) print len(t) s = '' str1 = 'Python is great!' str2 = "Yes, it is." str3 = "It's not like any other languages" str4 = 'Don\'t walk. "Run"' print str4 long_str = "This is a rather long string \ containing back slash and new line.\nGood!" print long_str multiline = """ While the rest of the world has been catching on to the Perl scripting language, the Linux commnunity, long since past the pleasing shock of Perl's power, has been catching on to a different scripting animal -- Python.""" print multiline print ml = ''' While the rest of the world has been catching on to the Perl scripting language, the Linux commnunity, long since past the pleasing shock of Perl's power, has been catching on to a different scripting animal -- Python.''' print ml a =\ 2 print a print print '\\abc\\' print print 'abc\tdef\tghi' print print 'a\nb\nc' print print 'a\012b\012c' str1 = 'First String' str2 = 'Second String' str3 = str1 + ' ' + str2 print str3 print str1 * 3 print print str1[2] print str1[1:-1] print len(str1) print print str1[0:len(str1)] str1[0] = 'f' str1[0:3] = 'abc' for c in 'abcd': print c, s = 'spam and egg' s = s[:4] + ', cheese, ' + s[5:] s format = 'name = %s, age = %s' format format % ('gslee', 24) letter = ''' 안녕하세요 %s님, 오늘 밤 파티에 참석해 주실 수 있나요? 그럼.. 이강성 드림''' name = '홍길동' print letter % name print names = ['한학신', '정인숙', '박미경'] for name in names: print letter % name print '-' * 40 print "%s -- %s -- %d -- %f -- %e" % ((1, 2), [3,4,5], 5, 5.3, 101.3) "%r -- %r" % ((1, 2), [3, 4, 5]) # str() 대신에 repr() 내장 함수 사용 "%3d -- %5.2f -- %.2e" % (5, 5.356, 101.3) a = 456 '%d -- %o -- %x -- %X' % (a, a, a, a) f = 1.23456789123456789 f # 유효숫자가 길게 나옴 print f # 유효숫자가 다소 짧게 나옴 print str(f) # 'print 객체'는 str(객체)의 수행 결과를 출력함 print print '%f' % f # 소수점 이하를 6개로 유지 print '%g' % f # 소수점 이하를 5개로 유지 g = 1.23456789123E30 g print g print str(g) print print '%f' % g print '%g' % g f = 1.23456789123456789 print f print str(f) print repr(f) # repr()은 유효 숫자를 길게 출력 print '%(이름)s -- %(전화번호)s' %{'이름':'이강성', '전화번호':5284} print '%(이름)s -- %(전화번호)s' %{'전화번호':5284, '이름':'이강성'} print '%(이름)s -- %(전화번호)s' %{'전화번호':5284, '이름':'이강성', '주소':'Seoul'} name = 'gslee' # vars() vars()['name'] name = 'gslee' phone = 5284 '%(name)s -- %(phone)s' % vars() import string t = string.Template('$page is $title') t.substitute({'page':2, 'title': 'The Best of Times'}) t = string.Template('$page *** $title ***') t.substitute({'page':2, 'title': 'The Best of Times'}) t = string.Template('$page *** $title ***') t.substitute({'page':2}) t = string.Template('$page: $title') t.safe_substitute({'page':3}) t = string.Template('$page: $title $$') t.substitute({'page':2, 'title':'The Best'}) s = 'i like programming.' print s.upper() print s.upper().lower() print 'I Like Programming'.swapcase() # 대문자는 소문자로, 소문자는 대문자로 변환 print s.capitalize() # 첫 문자를 대문자로 변환 print s.title() # 각 단어의 첫 문자를 대문자로 변환 s = 'i like programming, i like swimming.' print s.count('like') # 'like' 문자열이 출현한 횟수를 반환 print print s.find('like') # 'like'의 첫글자 위치 (offset)를 반환 print s.find('programming') # 'programming'의 첫글자 위치를 반환 print s.find('programmin') # 'programmin'의 첫글자 위치를 반환 print s.find('programmii') # 'programmii' 단어는 없기 때문에 -1 반환 print print s.find('like', 3) # offset=3 부터 'like'을 검색하여 'like'의 첫글자 위치 반환 print s.find('my') # 'my' 단어는 없기 때문에 -1 반환 print print s.rfind('like') # find('문자열')과 동일하지만 오른쪽부터 검색 print s.rfind('like', 23) # 오른쪽부터 검색하되 offset=23까지만 검색 print print s.index('like') # find('문자열')과 동일하지만 print s.index('my') # 찾고자 하는 문자열이 없으면 ValueError 반환 s = 'i like programming, i like swimming.' print s.index('like', 3) # find('문자열', offset)와 동일, 존재하지 않으면 에러 print s.rindex('like') # rfind('문자열')과 동일 print print s.startswith('i like') # 'i like'로 시작하는 문자열인지 판단 print s.startswith('I like') # 대소문자 구별 print print s.endswith('swimming.') # 'swimming.'로 끝나는 문자열인지 판단 print s.startswith('progr', 7) # 7번째 문자열이 'progr'로 시작하는지 판단 print ss = '0123' print ss.endswith('23', 0, 4) # 0(included)번째에서 4(excluded)번째 사이의 문자열이 '23'로 끝나는지 판단 print ss.endswith('12', 0, 3) # 0(included)번째에서 3(excluded)번째 사이의 문자열이 '12'로 끝나는지 판단 u = ' spam and ham ' print u.strip() #좌우 공백을 제거하여 새로운 스트링 생성 print u #스트링은 변경불가능 y = u.strip() #strip()는 새로운 스트링을 생성함 print y print print u.rstrip() #오른쪽 공백 제거 print u.lstrip() #왼쪽 공백 제거 print ' abc '.strip() print '><><><>'.strip('<>') #스트링 안에 지정된 모든문자를 좌우에서 제거 print '><><><>\n'.strip('<>') #좌우 끝쪽이 아닌 내부에 존재하는 지정문자는 제거되지 않음 print '><>bc<><><>\n'.strip('<>') print print u'\u4000\u4001abc\u4000' print u'\u4000\u4001abc\u4000'.strip(u'\u4000') print p = ' \t abc \t ' print p print p.strip() u = 'spam and ham' print u.replace('spam', 'spam, egg') #replace()는 새로운 스트링을 생성함 print u k = u.replace('spam', 'spam, egg') print k u = ' spam and ham ' print u.split() # 공백으로 분리 (모든 공백 제거 및 문자열 내의 단어 리스트를 얻을 수 있음) print u.split('and') # 'and'로 분리 print u2 = 'spam and ham\tegg\ncheese' print u2.split() u = 'spam ham\tegg\ncheese' t = u.split() # 문자열 내의 단어 리스트 t2 = ':'.join(t) # 리스트 t 내부의 각 원소들을 ':'로 연결한 문자열 반환 print type(t2) print t2 print t3 = ",".join(t) # 리스트 t 내부의 각 원소들을 ','으로 연결한 문자열 반환 print t3 print t4 = '\n'.join(t) # 리스트 t 내부의 각 원소들을 '\n'으로 연결한 문자열 반환 print t4 print u = "스팸 햄 계란 치즈" t = u.split() print t print t[0], t[1], t[2], t[3] print u2 = u"스팸 햄 계란 치즈" t2 = u2.split() print t2 print t2[0], t2[1], t2[2], t2[3] lines = '''first line second line third line''' print type(lines) lines2 = lines.splitlines() # 문자열을 라인 단위로 분리한 각 원소들을 지닌 리스트 반환 print type(lines2) print lines2 s = 'one:two:three:four' print s.split(':', 2) # 두 번만 분리하여 얻은 각 원소들을 리스트에 넣어 반환 print s.rsplit(':', 1) # 오른쪽 부터 분리하되 한 번만 분리하여 얻은 각 원소들을 리스트에 넣어 반환 u = 'spam and egg' c = u.center(60) # 60자리를 확보하되 기존 문자열을 가운데 정렬한 새로운 문자열 반환 print type(c) print c print u.ljust(60) # 60자리를 확보하되 기존 문자열을 왼쪽 정렬한 새로운 문자열 반환 print u.rjust(60) # 60자리를 확보하되 기존 문자열을 오른쪽 정렬한 새로운 문자열 반환 u = 'spam and egg' print u.center(60, '-') # 공백에 채워질 문자를 선택할 수 있음 print u.ljust(60, '-') print u.rjust(60, '-') print '1\tand\t2' print '1\tand\t2'.expandtabs() # 탭사이즈 조정, 기본 8자 간격 print '1\tand\t2'.expandtabs(8) print '1\tand\t2'.expandtabs(4) # 4자 간격으로 조정 print '1234'.isdigit() # 문자열 내의 Character들이 모두 숫자인가? print 'abcd'.isalpha() # 문자열 내의 Character들이 모두 영문자인가? print '1abc234'.isalnum() # 문자열 내의 Character들이 모두 영문자 또는 숫자인가? print 'abc'.islower() # 문자열 내의 Character들이 모두 소문자인가? print 'ABC'.isupper() # 문자열 내의 Character들이 모두 대문자인가? print '\t\r\n'.isspace() # 문자열 내의 Character들이 모두 공백 문자인가? print 'This Is A Title'.istitle() # 문자열이 Title 형식 (각 단어의 첫글자가 대문자)인가? s = '123' print s.zfill(5) # 5글자 자리 확보뒤 문자열을 쓰되 남는 공백에는 zero (0)를 채움 print 'goofy'.zfill(6) # 6글자 자리 확보뒤 ... import time start_time = time.time() s = '' for k in range(1000000): s += 'python' end_time = time.time() print end_time - start_time start_time = time.time() t = [] for k in range(1000000): t.append('python') s = ''.join(t) end_time = time.time() print end_time - start_time start_time = time.time() s = 'python' * 1000000 end_time = time.time() print end_time - start_time import string print string.digits print string.octdigits print string.hexdigits print string.letters print string.lowercase print string.uppercase print string.punctuation # 각종 기호들 print print string.printable # 인쇄 가능한 모든 문자들 print string.whitespace # 공백 문자들 '\011\012\013\014\015' x = 'a' print x in string.uppercase print x in string.lowercase d = string.letters + string.digits print d userid = raw_input('your id:') d = string.letters + string.digits for ch in userid: if ch not in d: print 'invalid user id' break print u'Spam and Egg' print a = 'a' b = u'bc' print type(a) print type(b) c = a + b # 일반 문자열과 유니코드를 합치면 유니코드로 변환 print type(c) print c print u'Spam \uB610 Egg' # 문자열 내에 유티코드 이스케이프 문자인 \uHHHH 사용가능, HHHH는 4자리 16진수 (unicode 포맷) a = unicode('한글', 'utf-8') # '한글' 문자열의 인코딩 방식을 'utf-8'형태로 인식시키면서 해당 문자열을 unicode로 변환 print type(a) print a a a.encode('utf-8') # unicode 타입의 문자열을 utf-8 방식으로 인코딩 print len('한글과 세종대왕') print len(unicode('한글과 세종대왕', 'utf-8')) #유니코드 타입의 문자열은 한글 문자열 길이를 올바르게 반환함 print len(u'한글과 세종대왕') u = unicode('한글과 세종대왕', 'utf-8') #유니코드 타입의 한글 문자열에 대해서는 인덱싱 및 슬라이싱이 올바르게 수행됨 print u[0] print u[1] print u[:3] print u[4:] print u[::-1] print u2 = u'한글과 세종대왕' print u2[0] print u2[1] print u2[:3] print u2[4:] print u2[::-1] print u3 = '한글과 세종대왕' print u3[0] print u3[1] print u3[:3] print u3[4:] print u3[::-1] print print ord('A') # ord(): 문자의 ASCII 코드값 반환 print chr(65) # char(): ASCII 코드 65를 지니는 문자를 반환 print ord(unicode('가', 'utf-8')) print ord(u'가') print hex(ord(unicode('가', 'utf-8'))) print hex(ord(u'가')) print print unichr(0xac00) print print '가' print print unichr(44032) i = 0 while i < 100: print unichr(0xac00 + i) i = i + 1 def add(a, b): "add(a, b) returns a+b" return a + b print add.__doc__ help(add) ?add