繁体   English   中英

在python 3中删除尾随空白

[英]Remove trailing white space in 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])

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

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

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

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

或者,您可以使用join:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM