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

感谢所有的帮助!这就是答案

4

2 回答 2

4

那是因为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.
于 2013-08-12T08:22:44.210 回答
0

您可以这样编写切片(不在打印返回值上):

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

或者,您可以使用加入:

' '.join(['*']*b)
于 2013-08-12T08:24:08.820 回答