![](/img/trans.png)
[英]Find the last element (digit) on each line and sum all that are even python 3
[英]Finding the last element (digit) on every line in a file (Python)
我正在從一個文本文件中讀取內容,因此需要在每一行上找到最后一個元素(數字)。 我不明白為什么此代碼無法正常運行,因為我已經在常規字符串上對其進行了嘗試,但是在這種情況下似乎並不適用。
f = open("file.txt", "r")
result = 0
for line in f:
string = str(f.read())
if string[-1:].isdigit() == True:
result = int(string[-1:])
else:
result = 40
print(result)
f.close()
文件file.txt
僅包含以下行
81 First line32
因此代碼應將結果打印出2
,但我只能得到40
,因為第一個條件永遠不會成立。 我究竟做錯了什么?
您的f.read()太多了。 這就是您所需要的:
f = open("file.txt", "r")
result = 0
for line in f:
if line[-1:].isdigit():
result = int(line[-1:])
else:
result = 40
print(result)
f.close()
另外, if string[-1:].isdigit() == True:
可以用if line[-1:].isdigit():
代替if line[-1:].isdigit():
您可能還想使用line.strip()
擺脫新行,否則比較將失敗。
f = open("file.txt", "r")
result = 0
for line in f:
l = line.strip()
if l[-1:].isdigit():
result = int(l[-1:])
else:
result = 40
print(result)
f.close()
問題在於,該行中的最后一個字符是行尾字符。 使用.strip()
刪除它(它也會刪除多余的空格)。
with open("file.txt", "r") as f:
for line in f:
lastchar = line.strip()[-1]
if lastchar.isdigit():
result = int(lastchar)
else:
result = 40
print(result)
這將按照您的問題單行打印2
。
81 First line32
它也適用於多行,為每行打印結果。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.