删除python 3中的尾部空格

时间:2013-08-12 08:18:33

标签: python for-loop python-3.x character trailing

我制作的程序有点麻烦。我得到它显示一个钻石,但我有一个问题,这是我的代码:

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

感谢您的帮助!这就是答案

2 个答案:

答案 0 :(得分: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.

答案 1 :(得分:0)

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

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

或者,您可以使用join:

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