2014-11-01 80 views
0
刪除空格

我寫的代碼以產生所述斐波納契數列由用戶所選擇的點,例如「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) 
+2

您沒有關於「list」表示的選擇,但您可以自己格式化輸出。 – jonrsharpe 2014-11-01 13:47:19

+0

我個人喜歡在某些情況下對待對象,因爲他們真的是,如果我認爲自定義https://gist.github.com/anonymous/edec7353fa8b61e66e2d – neiesc 2014-11-01 14:42:49

回答

2

當打印這樣的容器,其使用的空白已經決定在它的__repr__方法。你必須格式化輸出自己:

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

感謝您的幫助,這正是我需要:) – user3075452 2014-11-02 02:25:41

+0

@ user3075452很高興我能幫上忙。考慮接受我的答案與下方的勾號,以表明您的問題已關閉。謝謝。 :) – 2014-11-02 10:01:07

0

此代碼:

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

創建由您的號碼轉換爲字符串的新列表,請用逗號和括號之間打印出來加入它。

請注意,這不是最快和最簡單的方式做你想做的。