猿问

如何从这两个整数组成的字符串中分离出两个整数?

我有一份外部文件。文件的最后一行包含两个数字。我能够通过以下方式获得两个数字的字符串:


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 来进行赋值。


犯罪嫌疑人X
浏览 109回答 2
2回答

婷婷同学_

获取文件的最后一行后,您可以使用str.split():last_line = ''with open('test.txt') as f:    for line in f:        last_line = lineparts = last_line.split()   # split on whitespacesprint(parts[1])             # print second element

繁星coding

您应该使用 split() 函数。width = width.split(' ')[-1]width是你的字符串变量('['1', '10']']。通常出于性能考虑,你宁愿使用 split() 而不是正则表达式。
随时随地看视频慕课网APP

相关分类

Python
我要回答