Milan Lad
Milan Lad

Reputation: 25

How to put data on separate lines in python

This is my code:

 if mode == "1" and classname == "1":
            f = sorted(open("alphabetical test.txt").readlines())
             print(f)

Every time it prints the data from the file it prints it like this:

['A, 9, 6, 2\n', 'K, 10, 1, 2\n', 'M, 5, 3, 7\n', 'P, 3, 5, 9\n']

How can i get rid of the '\n' and how do i put them on separate lines?

Thanks.

Upvotes: 2

Views: 347

Answers (3)

miku
miku

Reputation: 188014

To remove whitespace and newlines from a string, you can use str.strip or their variants str.lstrip and str.rstrip, respectively. As for a pretty printer, there's pprint.

An example:

if mode == "1" and classname == "1":
    # use context manager to open (and close) file
    with open("alphabetical test.txt") as handle:
        # iterate over each sorted line in the file
        for line in sorted(handle):
            # print the line, but remove any whitespace before
            print(line.rstrip())

Upvotes: 1

PM 2Ring
PM 2Ring

Reputation: 55469

Change your

print(f)

To

print(''.join(f))

The string ''.join() method takes a list (or other iterable) of strings, and joins them into one big string. You can use any separator you like between the substrings, eg '---'.join(f) will put --- between each of the substrings.

The \n in your list of strings is the escape sequence for the newline character. So when you print that big string made by joining your list of strings then each of the original strings from the list will be printed on a separate line.

Upvotes: 4

Matt O
Matt O

Reputation: 1346

Just call .strip() on each line from the file:

f = sorted([line.strip() for line in open("alphabetical test.txt").readlines()])

Upvotes: 2

Related Questions