How to remove extra space for the 'print' command in python?
I'm new to python, I'm using v2.7
#Filename:ReverseNumber.py
data=int(raw_input("Enter any number: "))
print "Reverse of the number: ",
while data!=0:
开发者_JS百科 a=data%10
print a,
data=data/10
So the output should come like :
Enter any number: 123
Reverse of the number: 321
but instead of this in the second line it is printing one extra space before every number.
How to overcome this?
You could modify your approach in a number of ways:
Create a list of your values, then join them with a blank string for printing:
out = []
while data != 0:
out.append(data % 10)
data /= 10
print ''.join(map(str, out))
You could skip the whole integer conversion step and just reverse the incoming string:
data = '123'
print data[-1::-1]
You could skip the integer step and join the result of reversed:
data = '123'
print ''.join(reversed(data))
You could add a backspace
to your print commands for your numbers:
while data != 0:
print '\b%d' % (data % 10)
data /= 10
Hopefully one of those fits your requirements.
There is an implicit space when a
is printed.
From the python docs:
"A space is written before each object is (converted and) written, unless the output system believes it is positioned at the beginning of a line. This is the case (1) when no characters have yet been written to standard output, (2) when the last character written to standard output is a whitespace character except ' ', or (3) when the last write operation on standard output was not a print statement."
So try
print "Reverse of the number:",
One way is to not print it until you're ready to print the whole lot. Sample code follows using strings:
data = int (raw_input ("Enter any number: "))
if data == 0:
str = "0"
else:
str = ""
while data != 0:
str = "%s%d" % (str, data % 10)
data = data / 10
print "Reverse of the number: %s" % (str)
Make a empty variable for purpose of storing reversed number, append every digit to it in a loop and then do the printing.
a = ''
while data!=0:
a += data%10
data=data/10
print a
精彩评论