python共通関数およびモジュール(3)
2872 ワード
import math
print '%.20f' %math.pi
# math.ceil(i) # i ,i = 1.3 , 2
# math.floor(i) # , 。i = 1.4, 1
# math.pow(a, b) # a b
# math.sqrt(i) # i
2.stringモジュール.
注意python 2.0以降のバージョンではstringモジュールは呼び出す必要がなくなり、その方法はS.method()の形式で呼び出すように変更され、変数Sが文字列オブジェクトであればその関数方法を直接使用することができ、追加のimport再インポートは必要ありません.
str = 'aBc'
print str.upper() #
print str.lower() #
print str.capitalize() #
print str.swapcase() #
print str.find('a') # find ‘I’, 0, -1
print str.count('p') #
print str.replace("B", "b", 1) # , ,
print str.strip('0') # strip() 。
print str.lstrip('0') # strip() 。
print str.rstrip('0') # strip() 。
#
print str.isalnum() # ,
print str.isdigit() #
print str.isalpha() #
print str.islower() #
print str.isupper() #
print str.startswith('a') # a
print str.endswith('c') # c
3.クッキーモジュール.
# cookie,
import urllib2
import cookielib
# CookieJar cookie
cookie = cookielib.CookieJar()
# urllib2 HTTPCookieProcessor cookie
handler=urllib2.HTTPCookieProcessor(cookie)
# handler opener
opener = urllib2.build_opener(handler)
# open urllib2 urlopen , request
response = opener.open('
for item in cookie:
print 'Name = '+item.name
print 'Value = '+item.value
クッキーを取得してファイルに保存
# cookie
import cookielib
import urllib2
# cookie , cookie.txt
filename = 'cookie.txt'
# MozillaCookieJar cookie,
cookie = cookielib.MozillaCookieJar(filename)
# urllib2 HTTPCookieProcessor cookie
handler = urllib2.HTTPCookieProcessor(cookie)
# handler opener
opener = urllib2.build_opener(handler)
# , urllib2 urlopen
response = opener.open("
# cookie
cookie.save(ignore_discard=True, ignore_expires=True)
クッキーを利用してサイトにログインするシミュレーション
# cookie
import urllib
import urllib2
import cookielib
filename = 'cookie.txt'
# MozillaCookieJar cookie,
cookie = cookielib.MozillaCookieJar(filename)
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookie))
postdata = urllib.urlencode({
'stuid':'201200131012',
'pwd':'23342321'
})
# URL
loginUrl = '
# , cookie
result = opener.open(loginUrl,postdata)
# cookie cookie.txt
cookie.save(ignore_discard=True, ignore_expires=True)
# cookie ,
gradeUrl = '
#
result = opener.open(gradeUrl)
print result.read()