【问题标题】:A program that prints text into a text file将文本打印到文本文件中的程序
【发布时间】:2019-05-11 10:23:28
【问题描述】:

我需要创建一个程序来接收用户的身份证号码来创建学校注册系统,然后将信息导出到 .txt 文件中。我的问题是我没有写每个身份证。号码输入到新行,我需要帮助。

我已将每个 i.d.成一个列表,然后将它们全部加入一个字符串。现在我需要打印每个身份证。字符串中的数字在单独的行上。请告诉我在哪里插入“\n”,以便在 txt 文件的新行上打印。

# we first define the name of the file and set it to write mode
to_file = open("RegForm.txt" , "w")

# list variable for storing the received i.d. numbers
id_numbers = []

# asking the user to enter the number of students that will write the exam
num = int(input("Please enter the number of students that will sit for the exam: "))



# creating a loop that iterates over every student who is writing the exam
# we then append the list of id numbers with each new input we receive

for toFile in range(0, num):
    id_numbers.append(input("Enter your ID Number: " ))

# we create the variable string_of_nums which is joining the list into a single string
string_of_nums = " ".join(id_numbers)

# writing the id numbers onto the text file
to_file.write(string_of_nums)

# closing the file
to_file.close()

我需要它来打印每个身份证。单独一行的数字

【问题讨论】:

    标签: python


    【解决方案1】:

    string_of_nums = "\n".join(id_numbers)

    【讨论】:

      【解决方案2】:

      您想在每行的末尾添加换行符 ('\n'),因此在将行连接在一起时使用换行符作为连接字符串。

      string_of_nums = "\n".join(id_numbers)
      

      【讨论】:

        【解决方案3】:

        您当前的 string_of_nums 用空格分隔每个学生 ID。

        string_of_nums = " ".join(id_numbers)
        

        join()定义及用法

        join() 方法获取一个可迭代对象中的所有项目并将它们连接成一个字符串。 必须指定一个字符串作为分隔符。

        所以“”中的任何内容都将是您的字符串分隔符。

        所以要用换行符分隔每个学生,我们必须插入 \n:

        string_of_nums = "\n".join(id_numbers)
        

        【讨论】:

          猜你喜欢
          • 2015-05-05
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-08-08
          • 2017-08-07
          • 1970-01-01
          • 2011-03-03
          • 2013-11-16
          相关资源
          最近更新 更多