2013-08-12 209 views
1

對我製作的程序有點麻煩。我得到它顯示鑽石,但我有一個問題,這裏是我的代碼:刪除python中的尾部空白3

a = input("Enter width: ") 
a = int(a) 
b = a 
for i in range(a): 
    i = i + 1 
    b = a - i 
    text = " " * b + " " + "* " * i 
    print(text[:-1]) 
for i in range(a): 
    i = i + 1 
    b = a - i 
    text = " " * i + " " + "* " * b 
    print(text[:-1]) 

感謝您的所有幫助!這是答案

+0

首先:'I = I + 1'在'for'循環很奇怪。你爲什麼要改變循環中的迭代變量? – gefei

+0

@gefei我這樣做是因爲python循環從0開始,我需要它從1開始。 – NoviceProgrammer

+0

您的切片上的打印返回值。放在字符串上。 – njzk2

回答

1

這是因爲print不返回字符串,它返回None

>>> print(print("foo")) 
foo 
None 

也許你想做到這一點:

text = " " * i + " " + "* " * b 
print (text[:-1]) 

刪除尾隨空白更好地利用str.rstrip

>>> "foo ".rstrip() 
'foo' 

幫助上str.rstrip

>>> print (str.rstrip.__doc__) 
S.rstrip([chars]) -> str 

Return a copy of the string S with trailing whitespace removed. 
If chars is given and not None, remove characters in chars instead. 
0

你可以寫你的片這樣的(不是在打印返回值):

("* "*b)[:-1] 

,或者您可以使用加入:

' '.join(['*']*b)