python - 删除 python 3 中的尾随空格

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

感谢大家的帮助!这就是答案

最佳答案

那是因为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.

关于python - 删除 python 3 中的尾随空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18182325/

相关文章:

python-3.x - Beautifulsoup 过滤器 "find_all"结果,仅限于通过 Regex 的 .jpeg 文件

Python情感分类

python - 推断 numpy 数组中的 NaN 值

python - 如何在 python 中创建带循环的元组

javascript - 如何在循环内创建具有唯一变量名称的动态对象?

python - 在kv文件中使用add_widget

arrays - 用列表和元组索引 Numpy 数组会给出不同的结果?

python装饰器修改当前范围内的变量

python - 计算列表中的元组,无论元组中每个元素的顺序如何

matlab - 如何向量化依赖的 For 循环