How would I create a new line in Python? - 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))

Related

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

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

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.

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

python Printing One result per line

I show below part of a working script to verify twitter accounts that is giving me the results I want one besides the other, while I want to have them one per line including the title of the find
Example, the first three result are for followers, then how many others are being followed, and in how many lists the user is in, and its giving me the results all in one line something like this:
1350 257 27 and I want it to be as follows
Followers:1,350
Following: 257
Number of lists present: 27
I tried to use " ; " commas, "/n " ; but either it does not work or gives me a 500 Error
Here is the script
All help will be nice
Thank you
................
details = twitter.show_user(screen_name='xxxxxx')
print "content-type: text/html;charset=utf-8"
print
print"<html><head></head><body>"
print (details['followers_count']) #followers
print (details['friends_count'])# following
print (details['listed_count'])# In how many lists
... ....
Instead of the last three print lines, use string formatting to pass in the values.
print "Followers:{}\nFollowing: {}\nNumber of lists present: {}".format(
details['followers_count'], details['friends_count'], details['listed_count']
)
Take a look at the print function. You can write multiple arguments in a tab-separated line like:
print details['followers_count'], details['friends_count'], details['listed_count']
If you want more control over what you print use the join function:
# Add the parts you want to show
stringParts = []
for part in ['followers_count','friends_count','listed_count']:
stringParts.append( part + " = " + str(details[part]) )
seperator = "," # This will give you a comma seperated string
print seperator.join( stringParts )
You can use the % operator
print 'Followers: %s \nFollowing: %s \nNumber of lists present: %s' % (
details['followers_count'], details['friends_count'],
details['listed_count'])

Put function outputs to a list in Python [duplicate]

This question already has answers here:
How can I use `return` to get back multiple values from a loop? Can I put them in a list?
(2 answers)
How to concatenate (join) items in a list to a single string
(11 answers)
How can I print multiple things on the same line, one at a time?
(18 answers)
Closed 8 months ago.
The aim of the following program is to convert words in 4 characters from "This" to "T***", I have done the hard part getting that list and len working.
The problem is the program outputs the answer line by line, I wonder if there is anyway that I can store output back to a list and print it out as a whole sentence?
Thanks.
#Define function to translate imported list information
def translate(i):
if len(i) == 4: #Execute if the length of the text is 4
translate = i[0] + "***" #Return ***
return (translate)
else:
return (i) #Return original value
#User input sentense for translation
orgSent = input("Pleae enter a sentence:")
orgSent = orgSent.split (" ")
#Print lines
for i in orgSent:
print(translate(i))
On py 2.x you can add a , after print:
for i in orgSent:
print translate(i),
If you're on py 3.x, then try:
for i in orgSent:
print(translate(i),end=" ")
default value of end is a newline(\n), that's why each word gets printed on a new line.
Use a list comprehension and the join method:
translated = [translate(i) for i in orgSent]
print(' '.join(translated))
List comprehensions basically store the return values of functions in a list, exactly what you want. You could do something like this, for instance:
print([i**2 for i in range(5)])
# [0, 1, 4, 9, 16]
The map function could also be useful - it 'maps' a function to each element of an iterable. In Python 2, it returns a list. However in Python 3 (which I assume you're using) it returns a map object, which is also an iterable that you can pass into the join function.
translated = map(translate, orgSent)
The join method joins each element of the iterable inside the parentheses with the string before the .. For example:
lis = ['Hello', 'World!']
print(' '.join(lis))
# Hello World!
It's not limited to spaces, you could do something crazy like this:
print('foo'.join(lis))
# HellofooWorld!
sgeorge-mn:tmp sgeorge$ python s
Pleae enter a sentence:"my name is suku john george"
my n*** is s*** j*** george
You just need to print with ,. See last line of below pasted code part.
#Print lines
for i in orgSent:
print (translate(i)),
For your more understanding:
sgeorge-mn:~ sgeorge$ cat tmp.py
import sys
print "print without ending comma"
print "print without ending comma | ",
sys.stdout.write("print using sys.stdout.write ")
sgeorge-mn:~ sgeorge$ python tmp.py
print without ending comma
print without ending comma | print using sys.stdout.write sgeorge-mn:~ sgeorge$

Categories