Skip to main content
 首页 » 编程设计

python之在一行中打印文本文件中的文本

2025年05月04日15webabcd

下面的代码打印出这样的文本:

 John 
  Smith 
  02/07/1234 

首先它缩进了两行,我将如何更改代码以将其打印为: John Smith 02/07/1234 在一条线上?

with open("Forename") as f1, open("Surname") as f2, open("Date of birth") as f3: 
    for forename, surname, birthdate in zip(f1,f2,f3): 
        print (forename, surname, birthdate) 

请您参考如下方法:

尝试:

with open("Forename") as f1, open("Surname") as f2, open("Date of birth") as f3: 
    for forename, surname, birthdate in zip(f1,f2,f3): 
        print("{} {} {}".format(forename.strip(' \t\n\r'), surname.strip(' \t\n\r'), birthdate.strip(' \t\n\r'))) 

.strip('\t\n\r') 删除前导和尾随制表符返回和空格,.format() 格式化要打印的字符串一种很好的可控方式。