我有一份外部文件。文件的最后一行包含兩個數字。我能夠通過以下方式獲得兩個數字的字符串:with open("file.txt", "r") as file: width = file.readline() for column in file: pass現在我只剩下這兩個數字作為一個字符串,內容為“1 10”。我需要訪問該字符串的 10。我已經使用過:print(re.findall('\d+', column))它只給了我 ['1', '10'] 但我實際上只需要整數 10 來進行賦值。
2 回答

婷婷同學_
TA貢獻1844條經驗 獲得超8個贊
獲取文件的最后一行后,您可以使用str.split()
:
last_line = ''
with open('test.txt') as f:
? ? for line in f:
? ? ? ? last_line = line
parts = last_line.split()? ?# split on whitespaces
print(parts[1])? ? ? ? ? ? ?# print second element

繁星coding
TA貢獻1797條經驗 獲得超4個贊
您應該使用 split() 函數。
width = width.split(' ')[-1]
width
是你的字符串變量('['1', '10']']。通常出于性能考慮,你寧愿使用 split() 而不是正則表達式。
添加回答
舉報
0/150
提交
取消