出處 http://blog.csdn.net/sruru/article/details/7803208
一: python中有三個內建函數:列表,元組和字串,他們之間的互相轉換使用三個函數,str(),tuple()和list(),具體樣本如下所示:
>>> s = "xxxxx"
>>> list(s)
['x', 'x', 'x', 'x', 'x']
>>> tuple(s)
('x', 'x', 'x', 'x', 'x')
>>> tuple(list(s))
('x', 'x', 'x', 'x', 'x')
>>> list(tuple(s))
['x', 'x', 'x', 'x', 'x']
tuple expression To string
>>> str(tuple(s))
"('x', 'x', 'x', 'x', 'x')"
list expression To string
>>> str(list(s))
"('x', 'x', 'x', 'x', 'x')"
列表和元組 [值] 轉換為字串則必須依靠join函數:
>>> "".join(tuple(s))
'xxxxx'
>>> "".join(list(s))
'xxxxx'
二: 讀取檔案獲得一行資料,將其按單詞劃分開,各單詞直接空格數不確定: split()
f = open(FILE_NAME, 'r')
for line in f.readlines():
s_lt = line.split()
...
f.close()
三: 遠端連線讀取終端資訊案例:
read_until(), splitlines()
def telnet_remote2(): tel_obj = telnet_connect() rst_list = [] for s in pid_lst: tel_obj.write("showmem -P " +s+"\n") pidin_info = tel_obj.read_until("#") info_list = pidin_info.splitlines() rst_list = rst_list + info_list tel_obj.write("exit\n") return (rst_list)