下面的代码打印如下文本:
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)
答案 0 :(得分: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 :(得分: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()]))