我在读取带数字的.txt文件时遇到了一些麻烦,我尝试了多种方法,但仍然出现错误:
如果x%3 == 0:
TypeError:不是所有在格式化字符串期间转换的参数
以下是一些数字:
75158, 81917, 2318, 69039, 46112, 30323, 28184, 92597, 89159, 6579, 90155,
56960, 88247, 72470, 36266, 32693, 31542, 65354, 73315, 1440, 82950, 84901,
35835, 86530, 27137, 43235, 98977, 21224, 62530, 52675, 18297, 41055, 25597,
13878, 65430, 90050, 66844, 67605
这是我的代码:
from string import punctuation
file=open("test.txt","r+")
lines=file.read()
xx=''.join(ch for ch in lines if ch not in punctuation)
print(xx)
for x in xx:
if x % 3 == 0:
print(x)
file.close()
我想打印所有可被3整除的数字。
在尝试从此字符串进行int转换时,还会出现其他错误:int()的无效文字的基数为10:'75158 ....'
答案 0 :(得分:1)
您可以先阅读它,然后在逗号cmap = interp1([1 0 0; 1 1 0; 0 1 0], linspace(1, 3, 41));
上split
,然后再做,
:)
list comprehension
或正确的方法:)
>>> x = "75158, 81917, 2318, 69039, 46112, 30323, 28184, 92597, 89159, 6579, 90155, 56960, 88247, 72470, 36266, 32693, 31542, 65354, 73315, 1440, 82950, 84901, 35835, 86530, 27137, 43235, 98977, 21224, 62530, 52675, 18297, 41055, 25597, 13878, 65430, 90050, 66844, 67605"
>>>
>>> x.strip().split(',') # being careful since reading from a file may have newlines :)
['75158', ' 81917', ' 2318', ' 69039', ' 46112', ' 30323', ' 28184', ' 92597', ' 89159', ' 6579', ' 90155', ' 56960', ' 88247', ' 72470', ' 36266', ' 32693', ' 31542', ' 65354', ' 73315', ' 1440', ' 82950', ' 84901', ' 35835', ' 86530', ' 27137', ' 43235', ' 98977', ' 21224', ' 62530', ' 52675', ' 18297', ' 41055', ' 25597', ' 13878', ' 65430', ' 90050', ' 66844', ' 67605']
>>> [int(y) for y in x.split(',')]
[75158, 81917, 2318, 69039, 46112, 30323, 28184, 92597, 89159, 6579, 90155, 56960, 88247, 72470, 36266, 32693, 31542, 65354, 73315, 1440, 82950, 84901, 35835, 86530, 27137, 43235, 98977, 21224, 62530, 52675, 18297, 41055, 25597, 13878, 65430, 90050, 66844, 67605]
>>> [int(y) for y in x.split(',') if y and int(y) % 3]
[75158, 81917, 2318, 46112, 30323, 28184, 92597, 89159, 90155, 56960, 88247, 72470, 36266, 32693, 65354, 73315, 84901, 86530, 27137, 43235, 98977, 21224, 62530, 52675, 25597, 90050, 66844]
答案 1 :(得分:0)
您以字符串形式读取数字并尝试使用模运算符。同样,由于您用“,” 分隔数字,因此您必须先将数字分开,然后再将其添加到列表中。 解决方法如下:
numbers_file=open("numbers.txt","r")
my_numbers=numbers_file.read().split(',')
print (my_numbers)
for no in my_numbers:
temp="%s"%(no)
temp=int(temp)
if (temp%3 == 0):
print(no)