我在做Euler问题,现在在problem #8上,我想把这个1000位数的大数字复制到numberToProblem8.txt文件中,然后把它读到我的脚本中,但是我找不到一个好的方法来删除新行。有了这个密码:
hugeNumberAsStr = ''
with open('numberToProblem8.txt') as f:
for line in f:
aSingleLine = line.strip()
hugeNumberAsStr.join(aSingleLine)
print(hugeNumberAsStr)
我使用print()只检查它是否工作正常,它不工作。它不打印任何东西。我的代码怎么了?我用strip()删除所有垃圾,然后使用join()将清理后的行添加到hugeNumberAsStr中(需要一个字符串来连接这些行,稍后将使用int()),并对所有行重复该操作。 Here is the .txt file with a number in it.
字符串的join方法只需要一个iterable对象并将每个部分连接在一起。然后返回结果的串联字符串。如帮助中所述(结构连接)公司名称:
加入(…) S、 连接(iterable)->str
因此,join方法实际上并不能满足您的需要。 连接行应该更像:
^{pr2}$甚至:
这样就去掉了额外的一行代码。在
您需要执行
hugeNumberAsStr += aSingleLine
而不是hugeNumberAsStr.join(..)
str.join()
加入传递的迭代器并返回由str
连接的字符串值。它不会像您所想的那样更新hugeNumberAsStr
的值。您想用removed\n
创建一个新字符串。您需要将这些值存储在新字符串中。为此,您需要将内容附加到字符串中比如说:
甚至:
^{pr2}$我将其简化为以下内容,以便从该文件中获取编号:
相关问题 更多 >
编程相关推荐