如何将两个整数与这两个整数的字符串分开?
How do I separate two integers from a string of those two integers?
我有一个外部文件。文件的最后一行包含两个数字。我能够通过以下方式获得两个数字的字符串:
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 来完成作业。
您应该使用 split() 函数。
width = width.split(' ')[-1]
width
是您的字符串变量 ('['1', '10']')。通常您更愿意使用 split() 而不是正则表达式,因为性能。
获取文件的最后一行后,可以使用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
我有一个外部文件。文件的最后一行包含两个数字。我能够通过以下方式获得两个数字的字符串:
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 来完成作业。
您应该使用 split() 函数。
width = width.split(' ')[-1]
width
是您的字符串变量 ('['1', '10']')。通常您更愿意使用 split() 而不是正则表达式,因为性能。
获取文件的最后一行后,可以使用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