-1

Python issues: I need some help to figure it out why this code is printing 3 lines with a blank line between them. I want it to print every contact of a .txt starting with a specific letter. For example, if Z is = A, it will print:

Ariana

SSN:132664979

+1356974664

Abigail

SSN: 2658978133

+5765613197

..And so on with all contacts starting with "A". I don't know how to delete those blank spaces between each line with information.I want the code to print something like this:

Ariana
SSN:132664979
+1356974664
Abigail
SSN: 2658978133
+5765613197
...so on

I'd like to clarify that the .txt doesn't have any blank space between the data. So it is something the code is doing.

    Z=input("Enter the letter:")
    archive = open("agenda.txt", "r").readlines()
    print("List of people starting with that letter:")
    for i,line in enumerate(archive):
        if line.startswith(Z):
            print(archive[i])
            print(archive[i+1])
            print(archive[i+2])```



Thank you for your help.

3 Answers3

2

.readlines() includes the newline ('\n') character at the end of each line. I prefer to .strip() this when you read in the file.

with open('agenda.txt') as file:
    archive = [line.strip() for line in file.readlines()]
will-hedges
  • 1,254
  • 1
  • 9
  • 18
  • Honestly, I didn't know that .readlines() includes the NEWLINE CHARACTER AT THE END OF EACH LINE. That's a problem. – Rooney Moka Jun 15 '21 at 13:57
1
print(archive[i].strip())
print(archive[i+1].strip())
print(archive[i+2].strip())

use .strip() to remove new lines (\n)

virxen
  • 408
  • 4
  • 12
1

If you use .readlines() method, the lines will always end with a new line character(\n), these characters are treated as strings and not interpreted when not specifically using print() method.

Meaning the newline will be displayed as '\n'.

However when using print() these characters will be interpreted and will be displayed as new lines. Hence the empty lines.

The best solution would be replacing this line:

archive = open("agenda.txt", "r").readlines()

With this:

archive = open("agenda.txt", "r").read().splitlines()

.read() method returns all lines at once, .splitlines() splits on linebreak, it splits the result of read() into a list, with each line as an element.

And all the lines will not end with \n.