2009年7月24日 星期五

[python] 字串處理 去除空白strip() 分割split(' ')

python 3.0
strip(),split()己經被 str模組取代 或使用 string模組


>>> AA = " 1 abc "
>>> AA.strip()
'1 abc'
>>> print AA
' 1 abc '
>>> AA.strip().split(' ')
['1', 'abc']
>>>



fobj = file('datafile.txt', 'r')
#使用迴圏抓取文字檔內容,依空白作為分隔,取出資料後插入資料庫中.
# Insert the data to database.
for line in fobj:
#讀入一行,使用strip()去除(頭/尾)的空白,使用split('空白')分割為序列items[]
items = line.strip().split(' ')
#代入items[]序列,產生一個字典型態變數values{'key1':'data1','key2':'data2'}
values = {'id': items[0], 'name': items[1]}

#關閉開檔
fobj.close()

沒有留言: