2017-08-11 69 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=' ')