python3をいじる

よく使いそうな変更部分をいじった。floatの精度指定はどうやるんだろーなー

インストール

macportsでpython3.1.1をインストールした。

$ sudo port install python31

いじる

import sys
# print statement become built-in function
print("Hello, World!")
print("42", end="\n\n")
print("error!", file=sys.stderr)
print(*["no", "name", "age", "sex"], sep=',') # csv format

# format
print("{0}, {1}".format("hello", "world"))
print("int  : {0}".format(3))
print("float: {0}".format(1.2))
dic = {"name": "alice", "age":24, "sex":"female"}
print("{name} {age} {sex}".format(**dic), sep='\t')
print("{name} {sex} {age}".format(**dic), sep='\t')

# xrange is now obsolete
# range 'class' makes range object
print(range(10))       # => <class 'range'>
print(list(range(10))) # 
# map,filter
print(map)             # => <class 'map'> (not a function)
print(filter)          # => <class 'filter'> (not a function)
it = map(lambda x: x*x, range(10))
print(it)              # => <map object at ~> (map returns map object)
print(list(it))        # expand all item

# print all items
# map returns map object, and list class reveals all item.
# finally, all item will be printed on console.
list(map(print, ["one", "two", "three"]))

# unicode string can be used as variable
ストリング = "文字列"
#&#21464;量 = "世界〓好!" # utf-8の中国語の変数。はてなだと文字化ける
#print(*[ストリング, &#21464;量])
print(ストリング)

print(type(b"")) # => <class 'bytes'>
print(type(""))  # => <class 'str'>

# reload module
import imp
imp.reload(sys)

# variable scope for list comprehensions
i = "i"
print(i)
[i for i in range(10)]
print(i) # => "i" (python3), => 9 (~python2.6)

# dict comprehensions
d = {x:x*x for x in range(10)}
print(d)

# json
import json
jsondoc = json.dumps([{"name":"carol", "age":32}, 1, [1,2,3]])
print(jsondoc, type(jsondoc))
print(json.loads(jsondoc), type(json.loads(jsondoc)))

出力

Hello, World!
42

error!
no,name,age,sex
hello, world
int  : 3
float: 1.2
alice 24 female
alice female 24
range(0, 10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
<class 'map'>
<class 'filter'>
<map object at 0x6319f0>
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
one
two
three
文字列
<class 'bytes'>
<class 'str'>
i
i
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81}
[{"age": 32, "name": "carol"}, 1, [1, 2, 3]] <class 'str'>
[{'age': 32, 'name': 'carol'}, 1, [1, 2, 3]] <class 'list'>

printでいちいち括弧うつのめんどくさい。