Toggle menu
Toggle personal menu
Not logged in
Your IP address will be publicly visible if you make any edits.

Python3Tutorial: Difference between revisions

From ZeroWiki
imported>cho_hol
No edit summary
imported>skywave
No edit summary
Line 6: Line 6:


== 내용 ==
== 내용 ==
=== Whetting Your Appetite ===
=== Using the Python Interpreter ===
=== An Informal Introduction to Python ===
=== More Control Flow Tools ===
=== Data Structures ===
=== Modules ===
=== Input and Output ===
=== Input and Output ===
==== Fancier Output Formatting ====
==== Fancier Output Formatting ====

Revision as of 08:41, 23 May 2014

개요

내용

Whetting Your Appetite

Using the Python Interpreter

An Informal Introduction to Python

More Control Flow Tools

Data Structures

Modules

Input and Output

Fancier Output Formatting

str()

vs {{{repr()}}}

str()
사람이 읽기 위한 용도로 string으로 변환
repr()
{{{eval()}}}을 사용하기 위한 용도로 string으로 변환
>>> s = 'Hello, world.'
>>> str(s)
'Hello, world.'
>>> repr(s)
"'Hello, world.'"
str.format()

method를 이용하면 노가다를 뛰지 않고도 깔끔하게 출력이 가능

>>> for x in range(1, 3):
...     print('{0:2d} {1:3d} {2:4d}'.format(x, x*x, x*x*x))
...
 1   1    1
 2   4    8
 3   9   27
>>> print('The story of {1}, {0}, and {other}.'.format('Manfred','Bill',
                                                       other='Georg'))
The story of Bill, Manfred, and Georg.
>>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678}
>>> print('Jack: {0[Jack]:d}; Sjoerd: {0[Sjoerd]:d}; '
...       'Dcab: {0[Dcab]:d}'.format(table))
Jack: 4098; Sjoerd: 4127; Dcab: 8637678
>>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678}
>>> print('Jack: {Jack:d}; Sjoerd: {Sjoerd:d}; Dcab: {Dcab:d}'.format(**table))
Jack: 4098; Sjoerd: 4127; Dcab: 8637678
vars()

를 이용하면 local variables를 담은 dictionary를 얻을 수 있음. 위의 예제와 쓰면 궁합이 좋음.

str.rjust(n)

, {{{str.ljust(n)}}}, {{{str.center(n)}}}: n사이즈에 맞게 정렬된 string을 반환. str이 이미 n보다 길면 무시.

    • 이와 같은 문제를 해결하기 위해
str.ljust(n)[:n]

같은 짓을 가능.

str.zfill(n)
n사이즈에 맞게 0이 삽입된 string을 반환.
Old string formatting
%typeIndicator
    • 구식이다.
print(‘The value of PI is %5.3f.’ % math.pi)

Reading and Writing Files

open(filename, mode)
파일 열기
    • mode
    • ‘r’: 읽기 (기본값)
    • ‘w’: 쓰기
    • ‘a’: 이어쓰기
    • ‘r+’,’w+’: 쓰고 읽기
    • ‘b’: 바이너리로 열기 (없으면 텍스트로 읽음)
  • binary vs text
    • text mode에서는 line ending을 플랫폼에 맞는 형식으로 변환.
    • 따라서 text가 아닌 파일을 text 모드로 열면 파일이 변형될 수 있음.
Methods of File Objects
read(size)
    • size만큼 파일을 읽는다. size가 지정되지 않거나 음수면 메모리가 허용하는 만큼 읽음.
    • 끝에 도달하면 빈 string인 ‘’를 반환
readline()

/ {{{readlines()}}}

    • 한 줄 읽어오는 메소드/한줄씩 묶어서 리스트로 제공하는 메소드
    • list(file)로도 readlines와 같은 효과
    • 다음과 같이 for문을 이용할 수도 있음:
for line in f:
	print(line, end=’’)
write(string)
    • 파일에 string을 씁니다. string만 가능하니 다른 것을 쓰고 싶다면 str(object)로 변환 후 이용.
seek(index,from)
    • from
    • 0 : 파일의 시작점을 기준으로
    • 1 : 현재 보고 있는 바이트를 기준으로(tell()로 보이는 그거)
    • 2 : 파일의 마지막 바이트를 기준으로
tell()
    • 파일 내의 현재 지정하고 있는 바이트 위치를 알려줌
close()
    • 파일을 닫음. 닫고 나서 해당 파일을 쓰려고 하면 오류가 남.
closed
    • NOT A METHOD
    • 닫혔는지 여부를 boolean으로 알려줌
Saving structured data with json
import json
json.load(json file)

도 파일 읽기 시스템. 읽고 난 뒤에는 마지막으로 간다. 고로 여러번 읽을 수 없다.

json.dumps(obj)
obj를 json 형식으로 전환
json.dump(obj, file)
file에 쓰기