How do I insert empty lines in text output? [duplicate] - python

I am following a beginners tutorial on Python, there is a small exercise where I have to add an extra function call and print a line between verses, this works fine if I print an empty line in between function calls but if I add an empty print line to the end of my happyBirthday() I get an indent error, without the added print line all works fine though, any suggestions as to why?
Here is the code:
def happyBirthday(person):
print("Happy Birthday to you!")
print("Happy Birthday to you!")
print("Happy Birthday, dear " + person + ".")
print("Happy Birthday to you!")
print("\n") #error line
happyBirthday('Emily')
happyBirthday('Andre')
happyBirthday('Maria')

You can just do
print()
to get an empty line.

You will always only get an indent error if there is actually an indent error. Double check that your final line is indented the same was as the other lines -- either with spaces or with tabs. Most likely, some of the lines had spaces (or tabs) and the other line had tabs (or spaces).
Trust in the error message -- if it says something specific, assume it to be true and figure out why.

Python 2.x:
Prints a newline
print
Python 3.x:
You must call the function
print()
Source: https://docs.python.org/3.0/whatsnew/3.0.html

Don't do
print("\n")
on the last line. It will give you 2 empty lines.

Python's print function adds a newline character to its input. If you give it no input it will just print a newline character
print()
Will print an empty line. If you want to have an extra line after some text you're printing, you can a newline to your text
my_str = "hello world"
print(my_str + "\n")
If you're doing this a lot, you can also tell print to add 2 newlines instead of just one by changing the end= parameter (by default end="\n")
print("hello world", end="\n\n")
But you probably don't need this last method, the two before are much clearer.

The two common to print a blank line in Python-
The old school way:
print "hello\n"
Writing the word print alone would do that:
print "hello"
print

This is are other ways of printing empty lines in python
# using \n after the string creates an empty line after this string is passed to the the terminal.
print("We need to put about", average_passengers_per_car, "in each car. \n")
print("\n") #prints 2 empty lines
print() #prints 1 empty line

Related

Scrolling text in Python command line

Is it possible to create scrolling text in the Python command line by repeatedly updating the same line of text with small time.sleep() delays?
I believe that the \b (backspace) character can effectively move the cursor backward over text already written. I thought that combining this with end="" parameter in Python 3 might allow subsequent print commands to update a previous print command. With careful tracking of the length of the text and insertion of backspace and other characters it should be possible to create static lines of text that animate in place.
Unfortunately none of this works and even the \b character seems to do nothing:
word = input("Type something-> ")
print(word+"\b\b\bHello", end="")
print("New text")
Anyone got any ideas?
Many thanks,
Kw
Maybe you need carriage return, or \r. This takes you to the beginning of the line. It is the same effect as in a physical typewriter when you move your carriage to the beginning and overwrite whatever is there.
If you use this:
print("Hello", end=" ")
print("world")
The output will be:
Hello World
But if you use:
print("Hello", end="\r")
print("world")
The output will be only:
world

Python write newline without \n

Hey I need to write a string to a text file but i need it to not have a \n as I am using it as a database. The script works fine but doesnt actually write into a newline obviously because I strip()-ed it. I was wondering if there was a way around even in another language.
So far I tried:
textfile = open('pass.txt.','a')
ask = raw_input("[+] Do you want to append you own passwords(y/n)")
if ask == "y":
print "[+] Use quit_appender_now to quit adding string"
while True:
stri = raw_input("[+] Enter word to add-->")
if stri == "quit_appender_now":
break
else:
stri = stri + "\n"
textfile.write(stri.strip())
elif ask =="n":
pass
The reason I dont want to use \n is because of this code:
with open('pass.txt'),'r') as r_text:
for x in r_text:
print repr(x)
The above code will print out the string with \n. Is there any way to get around this?
For example if pass.txt had asdf in there print repr(x) would print asdf\n. I need it to print asdf
As far as I can tell, what you are asking for is impossible because a newline is \n!
To clarify, text files contain sequences of characters. The only way to divide them into lines is to use one or more characters as the end-of-line marker. That's all \n is. (See this answer, suggested by #Daniel's comment, for more details.)
So you can write without newlines, but your file will be one loooong line. If you want to display its contents with repr() but don't like seeing the newline, you'll have to strip it before you print it:
with open('pass.txt'),'r') as r_text:
for x in r_text:
x = x.rstrip("\n") # Don't discard spaces, if any
print repr(x)
If that doesn't solve your problem, then your problem really has no solution and you need to ask a different question about the ultimate purpose of the file you're trying to generate. Someone will point you to a solution other than "writing a newline without writing a newline".
You could make a definition to write a line to a file.
For example:
class Dummy():
def __init__(self):
print('Hello')
self.writeToFile('Writing a line')
self.writeToFile('Writing another line')
def writeToFile(self, value):
self.value = value
# Open file
file = open('DummyFile.txt', 'a')
# Write value to file.
file.write(value)
# Jump to a new line.
file.write('\n')
# close file
file.close()
Dummy()
If you then would read DummyFile.txt, you will not see the \n in the text.

Print single character at a time in loop

I want to print the characters in a line one at a time. What this code ends up doing is reading the entire line one character at a time (with a pause between each character, so I know it is iterating through the characters correctly) then when it finishes that line, it will print all of the characters at once.
for line in lines:
for ch in line:
print(ch, end = ' ')
os.system("pause")
However, if I do:
for line in lines:
for ch in line:
print(ch, end = '\n') #same effect as print(ch)
os.system("pause")
it will print one character with a newline, then a system pause.
Why will it not print correctly in the first scenario but work in the second?
Also, I just ran a random test:
print ("is", end=' ')
os.system("pause")
print("newline?")
It did not print my message until after the system pause. Why did it not print "is" before the pause? It seems like there is some hidden workings of the print() function than I am not understanding. Anyone have some explanations?
Your output is being buffered: the output is held until a newline is sent, because printing a single line all at once is more efficient than printing it a character at a time.
You can put sys.stdout.flush() after each print() if you like. Other solutions here. Personally I kinda like the wrapper one. You can combine that with a context manager that sets and restores stdout in a with block for maximum Pythonicity.

python: print using carriage return and comma not working

I need to print over one line in a loop (Python 3.x). Looking around on SO already, I put this line in my code:
print('{0} imported\r'.format(tot),)
However, it still prints multiple lines when looped through. I have also tried
sys.stdout.write('{0} imported\r'.format(tot))
but this doesn't print anything to the console...
Anyone know what's going on with this?
If you want to overwrite your last line you need to add \r (character return) and end="" so that you do not go to the next line.
values = range(0, 100)
for i in values:
print ("\rComplete: ", i, "%", end="")
print ("\rComplete: 100%")
In the first case, some systems will treat \r as a newline. In the second case, you didn't flush the line. Try this:
sys.stdout.write('{0} imported\r'.format(tot))
sys.stdout.flush()
Flushing the line isn't necessary on all systems either, as Levon reminds me -- but it's generally a good idea when using \r this way.
I prefer to use the solution of Jan but in this way:
values = range(0, 101)
for i in values:
print ("Complete: ", i, "%", end="\r")
print ()

Where does the newline come from in Python?

In Python when I do
print "Line 1 is"
print "big"
The output I get is
Line 1 is
big
Where does the newline come from? And how do I type both statements in the same line using two print statements?
print adds a newline by default. To avoid this, use a trailing ,:
print "Line 1 is",
print "big"
The , will still yield a space. To avoid the space as well, either concatenate your strings and use a single print statement, or use sys.stdout.write() instead.
From the documentation:
A '\n' character is written at the
end, unless the print statement ends
with a comma. This is the only action
if the statement contains just the
keyword print.
If you need full control of the bytes written to the output, you might want to use sys.stdout
import sys
sys.stdout.write("Line 1 is ")
sys.stdout.write("big!\n")
When not outputing a newline (\n) you will need to explicitly call flush, for your data to not be buffered, like so:
sys.stdout.flush()
this is standard functionality, use print "foo",

Categories

Resources