【问题标题】:How to use /n in Python3?如何在 Python3 中使用 /n?
【发布时间】:2021-08-29 17:56:51
【问题描述】:

为了逐行而不是逐行获取输出,我想开始使用 /n 命令。

这是我认为应该放置的一段代码:

password_for = input('This password is for: ')
your_pass =  'Your password for {} is: {}'.format(password_for, password)

save_path = '/Users/"MyUsername"/Desktop'
name_of_file = input("What is the name of the file: ")
completeName = os.path.join(save_path, name_of_file+".txt")
with open(completeName, "a+") as file1:
    file1.write(your_pass)

/n 命令应该用于获取应该写入(输出)的文本,逐行如下:

Input 1
input 2

但是现在输出是这样的:

Input1Input2

也许 /N 不是解决方案?告诉我!

【问题讨论】:

  • /n 命令是什么意思?
  • @tobias 我猜他的意思是换行。
  • 是的,我希望我的输入是:输入 1 输入 2 而现在是这样的:输入 1Input2
  • 使用\n - 表示新行。
  • 这能回答你的问题吗? How to append new data onto a new line

标签: python newline


【解决方案1】:

您可以将它与字符串连接运算符一起使用,即“+ 运算符”,如下所示:

file1.write(your_pass + '\n')

【讨论】:

    【解决方案2】:
    password_for = input('This password is for: ')
    your_pass =  'Your password for {} is: {}'.format(password_for, password)
    
    save_path = '/Users/"MyUsername"/Desktop'
    name_of_file = input("What is the name of the file: ")
    completeName = os.path.join(save_path, name_of_file+".txt")
    with open(completeName, "a+") as file1:
        file1.write(your_pass + '\n')  # You need to place '\n' here.
    

    【讨论】:

      【解决方案3】:

      某些字符必须“转义”才能将它们输入字符串。在这种情况下,您需要一个换行符,用 Python 写成 \n

      无论如何,回答你的问题:

      with open(completeName, "a+") as file1:
          file1.write(your_pass + '\n')
      

      这会将your_pass 中的字符串与包含一个换行符的字符串连接起来,然后调用file1.write

      【讨论】:

      • 感谢托拜厄斯!!因此,按照您的步骤,您可以重新路由结果,因此在这种情况下是换行符,然后将调用 file1.write。有道理!
      • 一个小的修正。 \n 是所有编程语言中的新行代码,至少我能想到,不仅仅是 Python。
      【解决方案4】:

      您只需将其添加到您的代码中:-

      + '\n'
      

      在最后一行:-

      file1.write(your_pass + '\n')
      

      【讨论】:

        猜你喜欢
        • 2021-06-23
        • 2012-08-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多