删除txt文件中的换行符

2024-09-28 18:50:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我在做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.


Tags: 文件intxtwithline数字stripprint
3条回答

字符串的join方法只需要一个iterable对象并将每个部分连接在一起。然后返回结果的串联字符串。如帮助中所述(结构连接)公司名称:

加入(…) S、 连接(iterable)->str

Return a string which is the concatenation of the strings in the
iterable.  The separator between elements is S.

因此,join方法实际上并不能满足您的需要。 连接行应该更像:

^{pr2}$

甚至:

hugeNumberAsString += line.strip()

这样就去掉了额外的一行代码。在

您需要执行hugeNumberAsStr += aSingleLine而不是hugeNumberAsStr.join(..)

str.join()加入传递的迭代器并返回由str连接的字符串值。它不会像您所想的那样更新hugeNumberAsStr的值。您想用removed\n创建一个新字符串。您需要将这些值存储在新字符串中。为此,您需要将内容附加到字符串中

比如说:

hugeNumberAsStr = open('numberToProblem8.txt').read()
hugeNumberAsStr = hugeNumberAsStr.strip().replace('\n', '')

甚至:

^{pr2}$

我将其简化为以下内容,以便从该文件中获取编号:

>>> int(open('numberToProblem8.txt').read().replace('\n',''))
731671765313306249192251196744265747423553491949349698352031277450632623957831801698480186947885184385861560789112949495459501737958331952853208805511125406987471585238630507156932909632952274430435576689664895044524452316173185640309871112172238311362229893423380308135336276614282806444486645238749303589072962904915604407723907138105158593079608667017242712188399879790879227492190169972088809377665727333001053367881220235421809751254540594752243525849077116705560136048395864467063244157221553975369781797784617406495514929086256932197846862248283972241375657056057490261407972968652414535100474821663704844031998900088952434506585412275886668811642717147992444292823086346567481391912316282458617866458359124566529476545682848912883142607690042242190226710556263211111093705442175069416589604080719840385096245544

相关问题 更多 >