![](/img/trans.png)
[英]How to get the specific multiple value out from a list in python and If the user input is equal to the mulitple values print output
[英]trying to get an output from a file using the user input value then print the value in python
我正在嘗試學習 python 並且我編寫了這個腳本,它沒有向我顯示正確的 output.. 我錯過了什么?
我有一個這樣的文本文件:
測試
測試1
測試2
測試3
測試4
#測試5
測試6
#測試7
#測試8
任務1:
這是我的代碼:
fopen=open('file1.txt',mode='r+')
fread=fopen.read()
fread2="\n".join([line.strip() for line in fread.splitlines() if not line.startswith('#')])
print(fread2)
fopen.close()
Output:
測試
測試1
測試2
測試3
測試4
測試6
注意:test5、7 和 8 沒有打印出來。 成功!
任務 2:
請參見以下代碼:
fopen=open('file1.txt',mode='r+')
fread=fopen.read()
fread2="\n".join([line.strip() for line in fread.splitlines() if not line.startswith('#')])
text=input("Enter text: ")
for x in fread2:
if text == "":
continue
if text in x:
print(x)
fopen.close()
Output
輸入文字:測試
我哪里錯了?
您的fread2是單個字符串,因此當您for x in fread2
您將迭代每個字母,而不是文件的每一行。 您可以通過執行以下操作來查看:
for x in fread2:
print(x)
您必須將所有行保存在列表中或迭代文件行。
例子
嘗試遵循此代碼:
fopen=open('file1.txt',mode='r+')
fread=fopen.read()
fread2=[]
for line in fread.splitlines():
if not line.startswith('#'):
fread2.append(line) #this is important!
#If you write "+=" you'll iterate on every single letter
text=input("Enter text: ")
for x in fread2:
if text in x:
print("I've found "+x)
fopen.close()
如果用戶寫“2”,您的 output 將是:
更新
根據評論中的要求,如果你想檢查用戶輸入是否等於你必須替換的文件行
if text in x:
和
if text==x:
所以,如果用戶寫“text” , “text2”、“text3”等行將不會被打印出來!
這是一個 output 示例:
如評論中所述, fread2
變量是一個包含所有行的大字符串。 當你遍歷一個字符串時,你就是在遍歷它的字符。 因此,循環的示例迭代是:
if "test" in "e":
print(x)
很容易看出這不是您想要的。
要解決此問題,您可以通過以下方式遍歷這些行:
for x in fread2.split("\n"):
但是,我個人認為一個更優雅的解決方案是首先將行保存在列表中,並且僅更改打印方式:
with open('file1.txt',mode='r+') as fopen:
fread = [line.strip() for line in fopen if not line.startswith('#')]
# first assignment
print(*fread, sep='\n')
#second assignment
text = input("Enter text: ")
for line in fread:
if text == line:
print(line)
請注意,我使用with
打開文件,這是慣用的打開方式。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.