我有這樣的代碼,我打的是純文本格式閱讀Python - 閱讀和行間打印?
Python文件:
from itertools import islice
def phones():
with open('phones.txt','r+') as f:
lines = islice(f, 2, 4) #lines 2 and 4 only
for line in f:
found_phone = line.find('Phone')
if found_phone != -1:
Phones = line[found_phone+len('Phone:'):]
print Phones
return Phones
phones()
我的問題是我想打印線2和4之間旁邊的「手機」這個詞, 它打印的每一個字我只想要2線和4
之間經過「手機」這是我的文本文件
First lines of Phones
Phone Blackberry #Line 2
Phone iPhone #Line 3
Phone Huawei #Line 4
Second lines of Phones
Phone Samsung
Phone LG
氏s是我的輸出:
我想只打印是線2和4 之間,我想這樣的輸出:
Blackberry
iPhone
Huawei
我試圖用itertools
做到這一點,但它不工作... 我在做什麼錯了?
'在F'行着眼於文件中的每一行。我認爲'爲了排隊'可能是你想要做的。 – asongtoruin
你也可以使用'startwith' https://docs.python.org/2/library/stdtypes.html#str.startswith,所以你不需要splice + find。 –