【问题标题】:How to get the dollar symbol to come after words? [closed]如何让美元符号出现在单词后面? [关闭]
【发布时间】:2018-11-20 13:21:59
【问题描述】:

这是我的代码:

a = open("1.txt","r+")
b = open("2.txt","r+")
for i in a.readlines(): 
    io=str(i)+"$"
    e = b.writelines(io)

a.close()
b.close()

我希望 $ 出现在单词之后,但它出现在它们之前。

enter image description here

【问题讨论】:

  • 欢迎来到 Stack Overflow!图片和屏幕截图可以很好地添加到帖子中,但请确保帖子在没有它们的情况下仍然清晰且有用。 不要发布代码或错误消息的图像。阅读why。而是直接将实际代码/消息复制并粘贴或键入到帖子中。
  • 欢迎来到 SO !您可能还阅读了how to ask a good question,目前在阅读您的问题标题时无法知道您的问题是什么
  • 请编辑此问题以使其更清晰,以便我们重新打开它。

标签: python python-2.7 file


【解决方案1】:

这是因为每行末尾都包含\n

io=str(i)+"$" 更改为:

io = i.rstrip() + "$" + '\n'

【讨论】:

    【解决方案2】:

    你可以试试这个,使用上下文管理器:

    with open("1.txt", "r") as inFile:
        with open("2.txt", "w") as outFile:
            for line in inFile:
                outFile.write(line.strip() + "$\n")
    

    要返回您的代码,您可以使用切片去除最后一个字符 \n,然后在末尾添加 $\n

    a = open("1.txt","r+")
    b = open("2.txt","r+")
    for i in a.readlines(): 
        io=i[:-1] + "$\n"
        e = b.write(io)
    
    a.close()
    b.close()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-13
      • 2011-04-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-13
      相关资源
      最近更新 更多