in fact this should not be a problem because it's fairly basic. I just want to print out an array of categories, but in one line and separated by comma.
for entry in categories:
print(entry, ", ", end='')
Until now it worked perfectly but now it doesn't print anything. If I delete the last part ", end=''" it works but then I can't get everything in one row without a new line for each category.
Can someone explain to me why it isn't working any more?
You are almost certainly experiencing output buffering by line. The output buffer is flushed every time you complete a line, but by suppressing the newline you never fill the buffer far enough to force a flush.
You can force a flush using flush=True (Python 3.3 and up) or by calling the flush() method on sys.stdout:
for entry in categories:
print(entry, ", ", end='', flush=True)
You could simplify that a little, make , the end value:
for entry in categories:
print(entry, end=', ', flush=True)
to eliminate the space between the entry and the comma.
Alternatively, print the categories as one string by using the comma as the sep separator argument:
print(*categories, sep=', ')
Check categories isn't empty - that'd make it print nothing - also I'd consider changing your code to make use of the sep argument instead (depending how large categories is):
print(*categories, sep=', ')
eg:
>>> categories = range(10)
>>> print(*categories, sep=', ')
0, 1, 2, 3, 4, 5, 6, 7, 8, 9
Then you don't have to worry about flushing/trailing separators etc...
Printing to the terminal in Python 3 is usually "line buffered". That is, the whole line is only printed to the terminal once a newline character is encountered.
To resolve this problem you should either print a new line at the end of the for loop, or flush stdout.
eg.
for entry in categories:
print(entry, ", ", end='')
print(end='', flush=True) # or just print() if you're not fussed about a newline
However, there are better ways of printing an array out. eg.
print(", ".join(str(entry) for entry in categories))
# or
print(*categories, sep=", ")
Related
Is there any way to clear an output after it's printed, for an example if we write a code for a countdown the printed value is immediately cleared and another value is printed in the same place which the previous output was printed.
import time
a = [5,4,3,2,1,0]
for i in a:
time.sleep(0.2)
print(i,end="",)
Here the output is printed on the same line but is there a way to clear an output to print the next value in the same position which the previous output was like in a loading screen or a countdown (like 'cls' in the command prompt but as a process while the program is still running).
I would really appreciate the help.
Flush the output and print a carriage return character to place the cursor at the beginning of the line:
import time
a = [5,4,3,2,1,0]
print() # start on a new line
for i in a:
time.sleep(0.2)
print(i, end="\r", flush=True)
print()
Note that this will not clear the line, so you might want to do this too:
for i in [500] + a:
time.sleep(0.2)
print('\033[K', i, sep='', end="\r", flush=True)
Where \033[K is the ANSI escape sequence to clear the line.
Something like this. Use \r for end argument of print() call.
import time
for x in range(5, -1, -1):
print(f'\033[KCounting down {x}', end='\r')
time.sleep(1)
print()
The last print() is to move your cursor to next line otherwise the shell will overwrite the last line and \033[K is the ANSI escape sequence to clear the line.
Can anyone tell me how I can add text to my output? I tried to do print('The cpt/stuff pets folder contains the following:' +(os.listdir('/Users/raelynsade/Documents/cpt180stuff/pets')) and I got an error so I'm not sure how to go about.
Also can anyone tell me how I can separate the two values on separate lines, its joining them together
print(os.path.getsize(os.path.join('/Users/raelynsade/Documents/cpt180stuff/pets/dogs', 'dognames.txt')), end='') print(os.path.getsize(os.path.join('/Users/raelynsade/Documents/cpt180stuff/pets/dogs', 'dogs.jpg')), end='')
print(os.listdir('/Users/raelynsade/Documents/cpt180stuff'))
print(os.listdir('/Users/raelynsade/Documents/cpt180stuff/cars'))
print(os.listdir('/Users/raelynsade/Documents/cpt180stuff/pets'))
print('The Documents/cpt180stuff/pets/cats folder contains the following:')
print(os.path.getsize(os.path.join('/Users/raelynsade/Documents/cpt180stuff/pets/cats', 'catnames.txt')), end='')
print(os.path.getsize(os.path.join('/Users/raelynsade/Documents/cpt180stuff/pets/cats', 'cats.jpg')), end='')
print('The Documents/cpt180stuff/pets/dogs folder contains the following:')
print(os.path.getsize(os.path.join('/Users/raelynsade/Documents/cpt180stuff/pets/dogs', 'dognames.txt')), end='')
print(os.path.getsize(os.path.join('/Users/raelynsade/Documents/cpt180stuff/pets/dogs', 'dogs.jpg')), end='')
No. 1 You can use str.format() for that:
print(f"The cpt/stuff pets folder contains the following: {os.listdir('/Users/raelynsade/Documents/cpt180stuff/pets')}")
No. 2 don't use print(end=""). If you want a newline every print, just use print(value). end="" removes the newline. Refer this
I do not understand why when inputing a space between the code with \t gives one space of line between the 'green' and 'Some things I learned so far:' output. When I use \n it gives two spaces inbetween. Shouldn't the space be the same for either \t and \n? I know that \t does tab and \n is new line. but I do not understand how \n does two spaces inbetween
Code is:
fav_num = {
'rachel':'blue',
'hannah':'green',
}
print(fav_num['rachel'])
print(fav_num['hannah'])
#6-3
coding_glossary = {
'list':'mutable type where you can store info',
'tuple':'immutable type similar to list',
'string':'simple line of code'
}
print('\t')
print('Some things I learned so far: \n')
print('What a list is:')
print(coding_glossary['list'])
Output is :
blue
green
Some things I learned so far:
What a list is:
mutable type where you can store info
Process finished with exit code 0
python's built-in print function has '\n' as end character implicitly.
print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False):
Print objects to the text stream file, separated by sep and followed by end. sep, end, file and flush, if present, must be given as keyword arguments
So, every time you run print() there is a '\n' character that gets printed implicitly unless you override the behavior by passing end= to it. (like end='' for instance)
Your code can be equivalently written:
#
print()
print(‘Some things I learned so far:’)
print()
#
print by default goes to the next line. try
print(" ",end = "")
so you can see '\t' more clearly.
Also, tab jumps to the next block. A block is usually 4 spaces.
Try this and notice where the . is:
print("\t", end=".\n")
print("A\t", end=".\n")
print("ABC\t", end=".\n")
print("ABCD\t", end=".\n")
The statement print('\t') is printing a tab, then returning to the next line, as the default print function automatically adds a newline. So you can't see the tab, but it is there. When you add \n to the end of the string you print, it adds a line return in addition to the default line return.
To remove the default line return, specify the 'end' parameter of the print function:
print('abcd\n', end='')
This will only include one line return.
By default print put a new line at the end, to modify this behavior you can set the end parameter with end=""
Example:
print("this will use 2 lines \n")
print("this will use 1 line")
print("this will use 1 line \n", end="")
Since print() does give an '\n' string at the end of each output the command print('\n') gives the commandline string '\t\n'.
For more details please see the following well documented post Link
"\n" character is a newline character and when you print "\n" it sets the cursor to a new line. print always sets a new line in the end by default. But you can change that behavior by setting the value of end argument to an empty string.
print("hello", end="")
"\t" is a tab character
for i in range(20):
print("current number is\t", I)
# current number is 0
# current number is 1
# current number is 2
# current number is 3
# current number is 4
# current number is 5
# current number is 6
# current number is 7
# current number is 8
# current number is 9
# current number is 10
# current number is 11
# current number is 12
# current number is 13
# current number is 14
# current number is 15
# current number is 16
# current number is 17
# current number is 18
# current number is 19
Find more magic characters which can be useful in your programs
I am using Python 2.7 and this is what I am working with
print( "Massa: ", line.count("massa"))
# trying to create a new line between these two lines
print( "Lorem: ",line.count("lorem")+1)
I tried this
print( "Massa: ", line.count("massa"))\n( "Lorem: ", line.count("lorem")+1)
and did not get the results I was looking for
If you mean that you want to print it with a single print statement, this will do it.
print "Massa: ", line.count("massa"), "\n", "Lorem: ", line.count("lorem")+1
Since you are using Python 2.7 I removed the enclosing brackets, otherwise the strings are treated as elements of a tuple. I have also added a new line character \n in the middle to separate the output into 2 lines.
If you print the itmes as 2 separate print statements a new line will appear between them:
print "Massa: ", line.count("massa")
print "Lorem: ", line.count("lorem")+1
I think you can just use:
print ""
to print a newline
\n creates a line break. You can pass it as a single string and use format to place your parameters.
print("Massa: {0}\nLorem: {1}".format(line.count("massa"), line.count("lorem")+1))
def digits_plus(test):
test=0
while (test<=3):
print str(test)+"+",
test = test+1
return()
digits_plus(3)
The output is:
0+ 1+ 2+ 3+
However i would like to get: 0+1+2+3+
Another method to do that would be to create a list of the numbers and then join them.
mylist = []
for num in range (1, 4):
mylist.append(str(num))
we get the list [1, 2, 3]
print '+'.join(mylist) + '+'
If you're stuck using Python 2.7, start your module with
from __future__ import print_function
Then instead of
print str(test)+"+",
use
print(str(test)+"+", end='')
You'll probably want to add a print() at the end (out of the loop!-) to get a new-line after you're done printing the rest.
You could also use the sys.stdout object to write output (to stdout) that you have more fine control over. This should let you output exactly and only the characters you tell it to (whereas print will do some automatic line endings and casting for you)
#!/usr/bin/env python
import sys
test = '0'
sys.stdout.write(str(test)+"+")
# Or my preferred string formatting method:
# (The '%s' implies a cast to string)
sys.stdout.write("%s+" % test)
# You probably don't need to explicitly do this,
# If you get unexpected (missing) output, you can
# explicitly send the output like
sys.stdout.flush()