Python \n gives two spaces in between output and \t gives one - python

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

Related

line it up next to each other (nummbers)?

so i do not want the results under each other. How can i line it up next to each other? Like 1 1 1 and not 1 under 1 under 1. I did not find any good information about that. I tried print(x,t) but it do not work for for loops or does it?
here
By default, print() appends a newline character to the end of the string.
To have it not do this, simply use the following:
print("Hello World!", end = "")

What causes this return() to create a SyntaxError?

I need this program to create a sheet as a list of strings of ' ' chars and distribute text strings (from a list) into it. I have already coded return statements in python 3 but this one keeps giving
return(riplns)
^
SyntaxError: invalid syntax
It's the return(riplns) on line 39. I want the function to create a number of random numbers (randint) inside a range built around another randint, coming from the function ripimg() that calls this one.
I see clearly where the program declares the list I want this return() to give me. I know its type. I see where I feed variables (of the int type) to it, through .append(). I know from internet research that SyntaxErrors on python's return() functions usually come from mistype but it doesn't seem the case.
#loads the asciified image ("/home/userX/Documents/Programmazione/Python projects/imgascii/myascify/ascimg4")
#creates a sheet "foglio1", same number of lines as the asciified image, and distributes text on it on a randomised line
#create the sheet foglio1
def create():
ref = open("/home/userX/Documents/Programmazione/Python projects/imgascii/myascify/ascimg4")
charcount = ""
field = []
for line in ref:
for c in line:
if c != '\n':
charcount += ' '
if c == '\n':
charcount += '*' #<--- YOU GONNA NEED TO MAKE THIS A SPACE IN A FOLLOWING FUNCTION IN THE WRITER.PY PROGRAM
for i in range(50):#<------- VALUE ADJUSTMENT FROM WRITER.PY GOES HERE(default : 50):
charcount += ' '
charcount += '\n'
break
for line in ref:
field.append(charcount)
return(field)
#turn text in a list of lines and trasforms the lines in a list of strings
def poemln():
txt = open("/home/gcg/Documents/Programmazione/Python projects/imgascii/writer/poem")
arrays = []
for line in txt:
arrays.append(line)
txt.close()
return(arrays)
#rander is to be called in ripimg()
def rander(rando, fldepth):
riplns = []
for i in range(fldepth):
riplns.append(randint((rando)-1,(rando)+1)
return(riplns) #<---- THIS RETURN GIVES SyntaxError upon execution
#opens a rip on the side of the image.
def ripimg():
upmost = randint(160, 168)
positions = []
fldepth = 52 #<-----value is manually input as in DISTRIB function.
positions = rander(upmost,fldepth)
return(positions)
I omitted the rest of the program, I believe these functions are enough to get the idea, please tell me if I need to add more.
You have incomplete set of previous line's parenthesis .
In this line:-
riplns.append(randint((rando)-1,(rando)+1)
You have to add one more brace at the end. This was causing error because python was reading things continuously and thought return statement to be a part of previous uncompleted line.

Unexpected newline happens after capitalize method

Why is the output forcing a new line on the result when there isn't a \n after print (message_2.capitalize())?
# Input example python script
# Apparently in python 3.6, inputs can take strings instead of only raw values back in v2.7
message_0 = "good morning!"
message_1 = "please enter something for my input() value:"
message_2 = "the number you entered is ... "
message_3 = "ok, now this time enter value for my raw_input() value:"
message_final1 = "program ended."
message_final2 = "thank you!"
print ("\n\n")
print (message_0.capitalize() + "\n")
input_num = input(message_1.capitalize())
print ("\n")
# This line is obsoleted in python 3.6. raw_input() is renamed to input() .
# raw_input_num = raw_input(message_3.capitalize())
# data conversion
print ("Converting input_num() variable to float...\n")
input_num = float(input_num)
print ("\n")
print (message_2.capitalize())
print (input_num)
print ("\n")
print (message_final1.capitalize() + " " + message_final2.capitalize())
Output is as follows:
Good morning!
Please enter something for my input() value:67.3
Converting input_num() variable to float...
The number you entered is ...
67.3
Program ended. Thank you!
print(), by default, will add a newline. So the two statements:
print (message_2.capitalize())
print (input_num)
will put a newline in between the message and the number.
Either pass in both objects to print to one print() call:
print(message_2.capitalize(), input_num)
or tell print() not to add a newline by setting the end argument to an empty string:
print(message_2.capitalize(), end='')
print(input_num)
Python's print() function's default behavior is to print a newline follwing the input string.
You can change this behavior by adding the optional parameter end:
print("My message", end="")
I've asked my friends around, and rather than just deleting my question I thought to add value to this site by sharing the answer :
# , operator here removes an unexpected newline. the print statement has a built in newline. That's why!
print (message_2.capitalize(),(input_num),"\n")
# Alternative way to display the answer
print (message_2.capitalize() + " " + str(input_num))
So the key is to use a comma operand or do a string operator on the answer.

How would I create a new line in Python?

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))

Why is print() not working anymore with python?

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=", ")

Categories