简体   繁体   中英

Printing text from text files in one line

The code below prints the text like this:

 John
  Smith
  02/07/1234

Firstly it indents two of the lines, how would I change the code to print it as: John Smith 02/07/1234 on one line?

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)

try:

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')))

the .strip(' \\t\\n\\r') removes leading and trailing tabs returns and spaces, the .format() formats your string to print in a nice control-able way.

Use .join and strip the whitespace from each name.

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()]))

As your questions does not explicitly specify Python, you may want to know that you do not need any program at all, if you are on a unixoid system (BSD, Linux, Mac OSX): just use the paste shell command:

paste -d ";" forename surname birthday

will yield

John;Smith;02/07/1234

if you do not specify the -d flag, a tab will be used to separate the entries. You may learn more about paste here: https://en.wikipedia.org/wiki/Paste_(Unix)

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=' ')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM