Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tut] How to Skip a Line in Python using \n?
1
How to Skip a Line in Python using \n?

5/5 – (1 vote)

[Image: python-logo-generic-reddit-1024x536.jpg]

Skip Line \n

Summary:
  • Python’s newline character
    Code:
    \n
    indicates the end of a line of text.

  • The built-in
    Code:
    print()
    function automatically adds a newline character
    Code:
    \n
    at the end.

  • You can customize this behavior of separating two lines using a single newline character
    Code:
    '\n'
    by changing the default
    Code:
    end='\n'
    argument of the
    Code:
    print()
    function to your desired string.

  • Another way to skip a line in the Python output is to add an empty
    Code:
    print()
    statement that will just print an empty line and do nothing else.

Python’s newline character to indicate the end of a line of text is
Code:
\n
.

If you print a string to the shell using the built-in
Code:
print()
function, Python automatically adds a newline character
Code:
\n
at the end.

Code:
PYTHON CODE: print('hello\nworld\n\nPython is great!') OUTPUT: hello world Python is great!

For example, if you iterate over the text in a file using a
Code:
for
loop and print each line in the loop body, the lines are separated with single new lines.

Code:
################################# # File: my_filename.txt # ################################# # My # # File # # Content # ################################# with open('my_filename.txt', 'r') as my_file: for line in my_file.readlines(): print(line) # Output: My File Content

You can customize this behavior of separating two lines using a single newline character
Code:
'\n'
by changing the default
Code:
end='\n'
argument of the
Code:
print()
function to your desired string.

For example, you can skip two lines in Python using
Code:
print(my_string, end='\n\n')
by chaining two newline characters
Code:
'\n\n'
.

Code:
with open('my_filename.txt', 'r') as my_file: for line in my_file.readlines(): print(line, end='\n\n') # Output: My File Content # End Output

Another way to skip a line in the Python output is to add an empty
Code:
print()
statement that will just print an empty line and do nothing else.

Code:
with open('my_filename.txt', 'r') as my_file: for line in my_file.readlines(): print(line) print() # Output: My File Content # End Output
Reply

Users browsing this thread:
1 Guest(s)


Forum Jump: