How to remove the space while printing with newline \n? [duplicate] - python

This question already has answers here:
Printing each item of a variable on a separate line in Python
(4 answers)
Closed 1 year ago.
Input:
a = input("enter-")
b = input("enter-")
c = input("enter-")
print(a, "\n", b, "\n", c, "\n")
Output:
enter-line1
enter-line2
enter-line3
line1
line2
line3
How to remove the space before line2 and line3?

You can use the argument sep of print. By default, the separator is space:
print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)
>>> print(a, b, c, sep='\n')
line1
line2
line3

The print() function has more arguments than string and looks like this
print(object(s), sep=separator, end=end, file=file, flush=flush)
Default separator is ' ' so space will be added between every element.
To print without spaces, you need to use it like this
print(a,"\n",b,"\n",c,"\n", sep='')

Using the print statement with Python and commas in between will naturally give spaces. For example, if I used print(a,b,c), then the output would be line1 line2 line3. Here, by using print(a,"\n",b,"\n",c,"\n"), you are putting a space after you put a newline. So either use separate print statements or use the "\n" as the separator between the arguments without using commas.

Related

Why does the output of this request add spaces? [duplicate]

This question already has answers here:
Print without space in python 3
(6 answers)
Closed 2 years ago.
print("Blah: [",blah_url,blah,"]<br>", file=f)
Output:
Blah: [ http://blah/Pages/Revision.aspx?projectId=541511cd-86bf-46fc-ae70-aec46e6030c7 blah ]<br>
The additional space after the open bracket "[" and before the close bracket "]" shouldn't be there.
It should look like this:
Blah: [http://blah/Pages/Revision.aspx?projectId=541511cd-86bf-46fc-ae70-aec46e6030c7 blah]<br>
I have confirmed there are no extra spaces in the data being supplied as the input.
The print function automatically adds spaces between each of the parameters. Try this (it overrides the adding of spaces):
print("Blah: [", blah_url, blah, "]", file=f, sep="")
or this (passing it in as one parameter):
print("Blah: [" + blah_url + blah + "]", file=f)

How to split string with new line character \n [duplicate]

This question already has answers here:
Split a string by a delimiter in python
(5 answers)
Closed 2 years ago.
I am trying to print by breaking a line based on character \n (new line). Below is the example:
line = "This is list\n 1.Cars\n2.Books\n3.Bikes"
I want to print the output as below:
This is list:
1.Cars
2.Books
3.Bikes
I used code as below:
line1 = line.split()
for x in line1:
print(x)
But its printing each word in different line. How to split the string based on only "\n"
Regards,
Arun Varma
The argument to split() specifies the string to use as a delimiter. If you don't give an argument it splits on any whitespace by default.
If you only want to split at newline characters, use
line1 = line.split('\n')
There's also a method specifically for this:
line1 = line.splitlines()

I am trying to print some list containing '\t' and '\n' . But as python is not printing it because it is thinking it as a special character [duplicate]

This question already has answers here:
In Python, is it possible to escape newline characters when printing a string?
(3 answers)
Closed 7 years ago.
I have a delim list . Now I want to print every element in delim list. But print funtion in python is printing everything except character like '\t' , '\n'. I know it is usual . But can I print this like normal characters or strings.
delim=['\t','\n',',',';','(',')','{','}','[',']','#','<','>']
for c in delim:
print c
It is giving output :
it is printing all the list skipping \t and \n
Change them to raw string literals by prefixing a r:
>>> print '\n'
>>> print r'\n'
\n
For your example this would mean:
delim=[r'\t',r'\n',',',';','(',')','{','}','[',']','#','<','>']
for c in delim:
print c
If you just want to print them differently use repr
for c in delim:
print repr(c)
Note: You will also see additional ' at the beginning and end of each string.

Print without a newline between two strings [duplicate]

This question already has answers here:
How to print without a newline or space
(26 answers)
Closed 9 years ago.
I want to print some text beside another text that has been printed before in python
for example
print("Hello")
a="This is a test"
print(a)
What I mean is to print like this "HelloThis is a test" not in next line I know I shoud use print("Hello",a) but I wanted to use seprated print commands!!!!
Use end='' in the first print call:
print("Hello", end='')
a = "This is a test"
print(a)
#HelloThis is a test
Help on print:
print(value, ..., sep=' ', end='\n', file=sys.stdout)
Prints the values to a stream, or to sys.stdout by default.
Optional keyword arguments:
file: a file-like object (stream); defaults to the current sys.stdout.
sep: string inserted between values, default a space.
end: string appended after the last value, default a newline.
If you are using python 2.7 (python tag on question) you can place a comma after the print to not return a new line.
print("hello"),
print("world")
Will print "helloworld" all one one line.
So in your case it will be:
print("Hello"),
print(a)
Or if your using python 3 (python3.x tag on question) use:
print("hello", end='')
print('world')
So in your case it will be:
print("Hello", end='')
print(a)

How can I suppress the newline after a print statement? [duplicate]

This question already has answers here:
How to print without a newline or space
(26 answers)
How can I print multiple things on the same line, one at a time?
(18 answers)
Closed last month.
I read that to suppress the newline after a print statement you can put a comma after the text. The example here looks like Python 2. How can it be done in Python 3?
For example:
for item in [1,2,3,4]:
print(item, " ")
What needs to change so that it prints them on the same line?
The question asks: "How can it be done in Python 3?"
Use this construct with Python 3.x:
for item in [1,2,3,4]:
print(item, " ", end="")
This will generate:
1 2 3 4
See this Python doc for more information:
Old: print x, # Trailing comma suppresses newline
New: print(x, end=" ") # Appends a space instead of a newline
--
Aside:
in addition, the print() function also offers the sep parameter that lets one specify how individual items to be printed should be separated. E.g.,
In [21]: print('this','is', 'a', 'test') # default single space between items
this is a test
In [22]: print('this','is', 'a', 'test', sep="") # no spaces between items
thisisatest
In [22]: print('this','is', 'a', 'test', sep="--*--") # user specified separation
this--*--is--*--a--*--test
Code for Python 3.6.1
print("This first text and " , end="")
print("second text will be on the same line")
print("Unlike this text which will be on a newline")
Output
>>>
This first text and second text will be on the same line
Unlike this text which will be on a newline
print didn't transition from statement to function until Python 3.0. If you're using older Python then you can suppress the newline with a trailing comma like so:
print "Foo %10s bar" % baz,
Because python 3 print() function allows end="" definition, that satisfies the majority of issues.
In my case, I wanted to PrettyPrint and was frustrated that this module wasn't similarly updated. So i made it do what i wanted:
from pprint import PrettyPrinter
class CommaEndingPrettyPrinter(PrettyPrinter):
def pprint(self, object):
self._format(object, self._stream, 0, 0, {}, 0)
# this is where to tell it what you want instead of the default "\n"
self._stream.write(",\n")
def comma_ending_prettyprint(object, stream=None, indent=1, width=80, depth=None):
"""Pretty-print a Python object to a stream [default is sys.stdout] with a comma at the end."""
printer = CommaEndingPrettyPrinter(
stream=stream, indent=indent, width=width, depth=depth)
printer.pprint(object)
Now, when I do:
comma_ending_prettyprint(row, stream=outfile)
I get what I wanted (substitute what you want -- Your Mileage May Vary)
There's some information on printing without newline here.
In Python 3.x we can use ‘end=’ in the print function. This tells it to end the string with a character of our choosing rather than ending with a newline. For example:
print("My 1st String", end=","); print ("My 2nd String.")
This results in:
My 1st String, My 2nd String.

Categories