在没有空格的python中打印列表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27174180/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 01:30:09  来源:igfitidea点击:

Printing lists in python without spaces

pythonprinting

提问by maria alejandra escalante

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

我正在做一个程序,将基数 ​​10 中的数字更改为基数 7,所以我这样做了:

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

但是如果数字是 210 它打印 4 2 0 我如何摆脱空格

回答by fredtantini

You can use join with list comprehension:

您可以将 join 与列表理解结合使用:

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

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

另外,不要list用作变量名,因为它是一个内置函数。

回答by Avinash Raj

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

回答by Wikiii122

Take a look at sys.stdout. It's a file object, wrapping standard output. As every file it has writemethod, 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.

看看sys.stdout。它是一个文件对象,包装标准输出。由于每个文件都有write方法,它接受字符串,并将其直接放入 STDOUT。它本身也不会更改或添加任何字符,因此当您需要完全控制输出时它很方便。

>>> 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,

回答by Vikas P

In python 3 you can do like this :

在python 3中,您可以这样做:

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

Your output will be like this if input = 4 :

如果 input = 4 ,您的输出将是这样的:

1234

1234

回答by Jay Soni

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

It you print listyou will get:

你打印list你会得到:

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

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

new_s = "".join(list)

If you print new_s:

如果您打印new_s

"jay"

“杰”

回答by bracoo

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

将列表转换为字符串,并替换空格。

strings = ['hello', 'world']

print strings

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

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

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