Printing lists in python without spaces

拜拜、爱过 提交于 2020-07-29 12:44:14

问题


I am doing 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 do i get rid of the spaces


回答1:


You can use join with list comprehension:

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

Also, don't use list as a variable name since it is a built-in function.




回答2:


In python 3 you can do like this :

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

Your output will be like this if input = 4 :

1234




回答3:


Take a look at sys.stdout. It's a file object, wrapping standard output. As every file it has write method, which takes string, and puts it directly to STDOUT. It also doesn't alter nor add any characters on it's own, so it's handy when you need to fully control your output.

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

Note two things

  • you have to pass string to the function.
  • you don't get newline after printing.

Also, it's handy to know that the construct you used:

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

is equivalent to (frankly a bit more efficient):

for i in list:
    print i,



回答4:


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



回答5:


Convert the list to a string, and replace the white spaces.

strings = ['hello', 'world']

print strings

>>>['hello', 'world']

print str(strings).replace(" ", "")

>>>['hello','world']



回答6:


s = "jay"
list = [ i for i in s ]

It you print list you will get:

['j','a','y']

new_s = "".join(list)

If you print new_s:

"jay"



来源:https://stackoverflow.com/questions/27174180/printing-lists-in-python-without-spaces

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!