【问题标题】:Remove white space from list output从列表输出中删除空格
【发布时间】:2014-11-01 13:46:08
【问题描述】:

我写的代码是生成斐波那契数列到用户选择的点,例如'10'会生成:

[1, 1, 2, 3, 5, 8, 13, 21, 34, 55]

问题是空白,我想知道是否可以让它像这样打印:

[1,1,2,3,5,8,13,21,34,55]

没有空格。

这是我正在使用的代码:

a=int(input("write the length of numbers you would like to see the fibonacci series for(by entering 0 or 1 the output will be [1,1]):  "))

if a<0:
     print("invalid entry please type a positive number")
else:        
    i=2
    fibs=[1,1]
    b=fibs[-2]
    c=fibs[-1]
    d=b+c
    while i<a :
        i=i+1
        b=fibs[-2]
        c=fibs[-1]
        d=b+c
        fibs.append(d)
print(fibs)

【问题讨论】:

标签: python list spaces


【解决方案1】:

当你打印一个这样的容器时,它对空格的使用已经在它的__repr__ 方法中决定了。您必须自己格式化输出:

print('[{}].format('",".join(map(str, fibs))))  # Instead of print(fibs).

【讨论】:

  • 感谢您的帮助,这正是我所需要的 :)
  • @user3075452 很高兴我能帮上忙。考虑接受我的回答,并在下方打勾以表明您的问题已关闭。谢谢你。 :)
【解决方案2】:

这段代码:

print('[{}]'.format(','.join([str(x) for x in fibs])))

创建一个由转换为字符串的数字组成的新列表,用逗号连接它并在大括号之间打印。

请注意,这不是做你想做的最快和最简单的方法

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-11-03
    • 2022-01-14
    • 1970-01-01
    • 2023-03-16
    • 2016-04-24
    • 2014-04-10
    • 2013-10-28
    • 2022-06-16
    相关资源
    最近更新 更多