Printing lists in python without spaces

I am making a program that changes a number in base 10 to base 7, so I did this:

num = int(raw_input(""))
mod = int(0)
list = []
while num> 0:
    mod = num%7
    num = num/7
    list.append(mod)
list.reverse()
for i in range (0,len(list)):
    print list[i],

      

But if the number is 210 it prints 4 2 0 how can I get rid of the spaces

+3


source to share


4 answers


You can use a list join:

>>> l=range(5)
>>> print l
[0, 1, 2, 3, 4]
>>> ''.join(str(i) for i in l)
'01234'

      



Also, do not use list

as a variable name, as this is a built-in function.

+5


source


Take a look at sys.stdout

. It is a file object that wraps standard output. How every file has a method write

that takes a string and puts it directly into STDOUT. It also doesn't modify or add any characters, so it comes in handy when you need full control over your output.

>>> import sys
>>> for n in range(8):
...     sys.stdout.write(str(n))
01234567>>> 

      

Pay attention to two things

  • you need to pass the string to the function.
  • after printing you will not get a new line.


Also, it's good to know that the construct you are using is:

for i in range (0,len(list)):
   print list[i],

      

equivalently (frankly a little more efficient):

for i in list:
    print i,

      

+1


source


Use list_comprehension.

num= int(raw_input(""))
mod=int(0)
list =[]
while num> 0:
    mod=num%7
    num=num/7
    list.append(mod)
list.reverse()
print ''.join([str(list[i]) for i in range (0,len(list))])

      

0


source


In python 3, you can do the following:

print(*range(1,int(input())+1), sep='')

      

Your output will be as if input = 4:

1234

0


source







All Articles