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]
a b f 200 900
print l[100]
--------------------------------------------------------------------------- IndexError Traceback (most recent call last) <ipython-input-2-dd85adc9a089> in <module>() ----> 1 print l[100] IndexError: list index out of range
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]
bc bcdef abcdef abcdef [100, 200] [100, 200]
s = 'abcd'
print s[::2] #step:2 - 오른쪽 방향으로 2칸씩
print s[::-1] #step:-1 - 왼쪽 방향으로 1칸씩
ac dcba
s = 'abc' + 'def'
print s
L = [1,2,3] + [4,5,6]
print L
abcdef [1, 2, 3, 4, 5, 6]
s = 'Abc'
print s * 4
L = [1,2,3]
print L * 2
AbcAbcAbcAbc [1, 2, 3, 1, 2, 3]
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
True True False True
print 'ab' in 'abcd'
print 'ad' in 'abcd'
print ' ' in 'abcd'
print ' ' in 'abcd '
True False False True
s = 'abcde'
l = [1,2,3]
t = (1, 2, 3, 4)
print len(s)
print len(l)
print len(t)
5 3 4
s = ''
str1 = 'Python is great!'
str2 = "Yes, it is."
str3 = "It's not like any other languages"
str4 = 'Don\'t walk. "Run"'
print str4
Don't walk. "Run"
long_str = "This is a rather long string \
containing back slash and new line.\nGood!"
print long_str
This is a rather long string containing back slash and new line. Good!
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
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. 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.
이스케이프 문자 | 의미 |
---|---|
\ | 라인 연속 |
\ \ | \ |
' | ' |
" | " |
\b | 백스페이스 |
\n (또는 \012) | 개행 |
\t | 탭 |
\0nn | 8진법 수 nn |
\xnn | 16진법 수 nn |
a =\
2
print a
print
print '\\abc\\'
print
print 'abc\tdef\tghi'
print
print 'a\nb\nc'
print
print 'a\012b\012c'
2 \abc\ abc def ghi a b c a b c
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)]
First String Second String First StringFirst StringFirst String r irst Strin 12 First String
str1[0] = 'f'
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-47-7213ba3e679f> in <module>() ----> 1 str1[0] = 'f' TypeError: 'str' object does not support item assignment
str1[0:3] = 'abc'
--------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-48-08d42bad7f22> in <module>() ----> 1 str1[0:3] = 'abc' TypeError: 'str' object does not support item assignment
for c in 'abcd':
print c,
a b c d
s = 'spam and egg'
s = s[:4] + ', cheese, ' + s[5:]
s
'spam, cheese, and egg'
format = 'name = %s, age = %s'
format
'name = %s, age = %s'
format % ('gslee', 24)
'name = gslee, age = 24'
letter = '''
안녕하세요 %s님,
오늘 밤 파티에 참석해 주실 수 있나요?
그럼..
이강성 드림'''
name = '홍길동'
print letter % name
print
names = ['한학신', '정인숙', '박미경']
for name in names:
print letter % name
print '-' * 40
print
안녕하세요 홍길동님, 오늘 밤 파티에 참석해 주실 수 있나요? 그럼.. 이강성 드림 안녕하세요 한학신님, 오늘 밤 파티에 참석해 주실 수 있나요? 그럼.. 이강성 드림 ---------------------------------------- 안녕하세요 정인숙님, 오늘 밤 파티에 참석해 주실 수 있나요? 그럼.. 이강성 드림 ---------------------------------------- 안녕하세요 박미경님, 오늘 밤 파티에 참석해 주실 수 있나요? 그럼.. 이강성 드림 ----------------------------------------
포맷팅 문자 | 설명 |
---|---|
%s | 문자열을 포함한 임의의 객체를 문자열로 변환하여 출력 (str() 내장 함수 사용) |
%r | 문자열을 포함한 임의의 객체를 문자열로 변환하여 출력 (repr() 내장 함수 사용) |
%c | 1글자 문자 (ex. '%c' % 'k) |
%d | 10진 정수 (%5d: 5자리를 확보한 후 정수 포맷팅) |
%i | %d와 동일 |
%u | 부호 없는 정수. 음수는 양수처럼 해석함 (ex. '%u' % -12 --> '4294967284') |
%o | 8진수 정수 (ex. '%o' % 13 --> 15) |
%x | 16진수 정수 (소문자 표현) (ex. '%x' % 13 --> 'd') |
%X | 16진수 정수 (대문자 표현) (ex. '%X' % 13 --> 'D') |
%e | 부동 소수점 실수를 지수 형태로 표현 (%.2e: 2자리는 소수점 이하 자리수) |
%E | %e 와 동일 (대문자 E 표현) |
%f | 부동 소수점 실수 (%5.2f: 소수점 포함 총 5자리 확보한 후 2자리는 소수점 이하 자리수) |
%g | 부동 소수점을 편의에 따라 일반 실수 형식이나 지수 형식으로 변환 |
%G | %g와 동일 (대문자 E 표현) |
"%s -- %s -- %d -- %f -- %e" % ((1, 2), [3,4,5], 5, 5.3, 101.3)
'(1, 2) -- [3, 4, 5] -- 5 -- 5.300000 -- 1.013000e+02'
"%r -- %r" % ((1, 2), [3, 4, 5]) # str() 대신에 repr() 내장 함수 사용
'(1, 2) -- [3, 4, 5]'
"%3d -- %5.2f -- %.2e" % (5, 5.356, 101.3)
' 5 -- 5.36 -- 1.01e+02'
a = 456
'%d -- %o -- %x -- %X' % (a, a, a, a)
'456 -- 710 -- 1c8 -- 1C8'
f = 1.23456789123456789
f # 유효숫자가 길게 나옴
1.234567891234568
print f # 유효숫자가 다소 짧게 나옴
print str(f) # 'print 객체'는 str(객체)의 수행 결과를 출력함
print
print '%f' % f # 소수점 이하를 6개로 유지
print '%g' % f # 소수점 이하를 5개로 유지
1.23456789123 1.23456789123 1.234568 1.23457
g = 1.23456789123E30
g
1.23456789123e+30
print g
print str(g)
print
print '%f' % g
print '%g' % g
1.23456789123e+30 1.23456789123e+30 1234567891230000003315149045760.000000 1.23457e+30
f = 1.23456789123456789
print f
print str(f)
print repr(f) # repr()은 유효 숫자를 길게 출력
1.23456789123 1.23456789123 1.234567891234568
print '%(이름)s -- %(전화번호)s' %{'이름':'이강성', '전화번호':5284}
print '%(이름)s -- %(전화번호)s' %{'전화번호':5284, '이름':'이강성'}
print '%(이름)s -- %(전화번호)s' %{'전화번호':5284, '이름':'이강성', '주소':'Seoul'}
이강성 -- 5284 이강성 -- 5284 이강성 -- 5284
name = 'gslee'
# vars()
vars()['name']
'gslee'
name = 'gslee'
phone = 5284
'%(name)s -- %(phone)s' % vars()
'gslee -- 5284'
import string
t = string.Template('$page is $title')
t.substitute({'page':2, 'title': 'The Best of Times'})
'2 is The Best of Times'
t = string.Template('$page *** $title ***')
t.substitute({'page':2, 'title': 'The Best of Times'})
'2 *** The Best of Times ***'
t = string.Template('$page *** $title ***')
t.substitute({'page':2})
--------------------------------------------------------------------------- KeyError Traceback (most recent call last) <ipython-input-14-cc54456d33c2> in <module>() 1 t = string.Template('$page *** $title ***') ----> 2 t.substitute({'page':2}) /Applications/Canopy.app/appdata/canopy-1.4.1.1975.macosx-x86_64/Canopy.app/Contents/lib/python2.7/string.pyc in substitute(self, *args, **kws) 170 raise ValueError('Unrecognized named group in pattern', 171 self.pattern) --> 172 return self.pattern.sub(convert, self.template) 173 174 def safe_substitute(self, *args, **kws): /Applications/Canopy.app/appdata/canopy-1.4.1.1975.macosx-x86_64/Canopy.app/Contents/lib/python2.7/string.pyc in convert(mo) 160 named = mo.group('named') or mo.group('braced') 161 if named is not None: --> 162 val = mapping[named] 163 # We use this idiom instead of str() because the latter will 164 # fail if val is a Unicode containing non-ASCII characters. KeyError: 'title'
t = string.Template('$page: $title')
t.safe_substitute({'page':3})
'3: $title'
t = string.Template('$page: $title $$')
t.substitute({'page':2, 'title':'The Best'})
'2: The Best $'
s = 'i like programming.'
print s.upper()
print s.upper().lower()
print 'I Like Programming'.swapcase() # 대문자는 소문자로, 소문자는 대문자로 변환
print s.capitalize() # 첫 문자를 대문자로 변환
print s.title() # 각 단어의 첫 문자를 대문자로 변환
I LIKE PROGRAMMING. i like programming. i lIKE pROGRAMMING I like programming. I Like Programming.
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 반환
2 2 7 7 -1 22 -1 22 -1 2
--------------------------------------------------------------------------- ValueError Traceback (most recent call last) <ipython-input-4-5ef249529479> in <module>() 14 print 15 print s.index('like') # find('문자열')과 동일하지만 ---> 16 print s.index('my') # 찾고자 하는 문자열이 없으면 ValueError 반환 ValueError: substring not found
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'로 끝나는지 판단
22 22 True False True True True True
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 '><><abc<><><>'.strip('<>') #스트링 안에 지정된 모든문자를 좌우에서 제거
spam and ham spam and ham spam and ham spam and ham spam and ham abc abc
print '><><abc<><><>\n'.strip('<>') #좌우 끝쪽이 아닌 내부에 존재하는 지정문자는 제거되지 않음
print '><><a<>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()
abc<><><> a<>bc<><><> 䀀䀁abc䀀 䀁abc abc abc
u = 'spam and ham'
print u.replace('spam', 'spam, egg') #replace()는 새로운 스트링을 생성함
print u
k = u.replace('spam', 'spam, egg')
print k
spam, egg and ham spam and ham spam, egg and ham
u = ' spam and ham '
print u.split() # 공백으로 분리 (모든 공백 제거 및 문자열 내의 단어 리스트를 얻을 수 있음)
print u.split('and') # 'and'로 분리
print
u2 = 'spam and ham\tegg\ncheese'
print u2.split()
['spam', 'and', 'ham'] [' spam ', ' ham '] ['spam', 'and', 'ham', 'egg', 'cheese']
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
<type 'str'> spam:ham:egg:cheese spam,ham,egg,cheese spam ham egg cheese
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]
['\xec\x8a\xa4\xed\x8c\xb8', '\xed\x96\x84', '\xea\xb3\x84\xeb\x9e\x80', '\xec\xb9\x98\xec\xa6\x88'] 스팸 햄 계란 치즈 [u'\uc2a4\ud338', u'\ud584', u'\uacc4\ub780', u'\uce58\uc988'] 스팸 햄 계란 치즈
lines = '''first line
second line
third line'''
print type(lines)
lines2 = lines.splitlines() # 문자열을 라인 단위로 분리한 각 원소들을 지닌 리스트 반환
print type(lines2)
print lines2
<type 'str'> <type 'list'> ['first line', 'second line', 'third line']
s = 'one:two:three:four'
print s.split(':', 2) # 두 번만 분리하여 얻은 각 원소들을 리스트에 넣어 반환
print s.rsplit(':', 1) # 오른쪽 부터 분리하되 한 번만 분리하여 얻은 각 원소들을 리스트에 넣어 반환
['one', 'two', 'three:four'] ['one:two:three', 'four']
u = 'spam and egg'
c = u.center(60) # 60자리를 확보하되 기존 문자열을 가운데 정렬한 새로운 문자열 반환
print type(c)
print c
print u.ljust(60) # 60자리를 확보하되 기존 문자열을 왼쪽 정렬한 새로운 문자열 반환
print u.rjust(60) # 60자리를 확보하되 기존 문자열을 오른쪽 정렬한 새로운 문자열 반환
<type 'str'> spam and egg spam and egg spam and egg
u = 'spam and egg'
print u.center(60, '-') # 공백에 채워질 문자를 선택할 수 있음
print u.ljust(60, '-')
print u.rjust(60, '-')
------------------------spam and egg------------------------ spam and egg------------------------------------------------ ------------------------------------------------spam and egg
print '1\tand\t2'
print '1\tand\t2'.expandtabs() # 탭사이즈 조정, 기본 8자 간격
print '1\tand\t2'.expandtabs(8)
print '1\tand\t2'.expandtabs(4) # 4자 간격으로 조정
1 and 2 1 and 2 1 and 2 1 and 2
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 형식 (각 단어의 첫글자가 대문자)인가?
True True True True True True True
s = '123'
print s.zfill(5) # 5글자 자리 확보뒤 문자열을 쓰되 남는 공백에는 zero (0)를 채움
print 'goofy'.zfill(6) # 6글자 자리 확보뒤 ...
00123 0goofy
import time
start_time = time.time()
s = ''
for k in range(1000000):
s += 'python'
end_time = time.time()
print end_time - start_time
0.23934006691
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
0.152743816376
start_time = time.time()
s = 'python' * 1000000
end_time = time.time()
print end_time - start_time
0.00288701057434
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'
0123456789 01234567 0123456789abcdefABCDEF ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ !"#$%&'()*+,-./:;<=>?@[\]^_`{|}~ 0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~
x = 'a'
print x in string.uppercase
print x in string.lowercase
False True
d = string.letters + string.digits
print d
ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789
userid = raw_input('your id:')
your id:ab#
d = string.letters + string.digits
for ch in userid:
if ch not in d:
print 'invalid user id'
break
invalid user id
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
Spam and Egg <type 'str'> <type 'unicode'> <type 'unicode'> abc
print u'Spam \uB610 Egg' # 문자열 내에 유티코드 이스케이프 문자인 \uHHHH 사용가능, HHHH는 4자리 16진수 (unicode 포맷)
Spam 또 Egg
a = unicode('한글', 'utf-8') # '한글' 문자열의 인코딩 방식을 'utf-8'형태로 인식시키면서 해당 문자열을 unicode로 변환
print type(a)
print a
a
<type 'unicode'> 한글
u'\ud55c\uae00'
a.encode('utf-8') # unicode 타입의 문자열을 utf-8 방식으로 인코딩
'\xed\x95\x9c\xea\xb8\x80'
print len('한글과 세종대왕')
print len(unicode('한글과 세종대왕', 'utf-8')) #유니코드 타입의 문자열은 한글 문자열 길이를 올바르게 반환함
print len(u'한글과 세종대왕')
22 8 8
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를 지니는 문자를 반환
65 A
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)
44032 44032 0xac00 0xac00 가 가 가
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__
add(a, b) returns a+b
help(add)
Help on function add in module __main__: add(a, b) add(a, b) returns a+b
?add