2017-08-11 142 views
1

下面的代码打印这样的文字:打印文本在一行

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) 

回答

3

尝试:

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()格式,您的字符串以可控的方式进行打印。

+1

如果使用不带参数的(),然后将它修剪所有空格字符,因此调用如forename.strip()就足够了。 – Arminius

+0

另外,在括号内为字符串本身添加一些空格:) – droravr

2

使用.join并从每个名称中去掉空格。

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(' '.join([forename.strip(), surname.strip(), birthdate.strip()])) 
1

由于您的问题没有明确指定的Python,你可能想知道,你不需要任何程序可言,如果你是一个unixoid系统(BSD,Linux和Mac OSX版)上:只使用paste shell命令:

paste -d ";" forename surname birthday 

将产生

John;Smith;02/07/1234 

如果不指定-d标志,标签将被用于条目分开。您可以了解更多关于paste这里:https://en.wikipedia.org/wiki/Paste_(Unix)

0
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, end=' ')