简体   繁体   English

在python 3中删除尾随空白

[英]Remove trailing white space in python 3

Having bit of trouble with a program i made. 我制作的程序有点麻烦。 i am getting it to display a diamond but i have a problem, here is my code: 我正在显示钻石,但是有一个问题,这是我的代码:

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

Thanks for all the help! 感谢您的所有帮助! this is the answer 这就是答案

That's because print doesn't return the string, it returns None . 那是因为print不返回字符串,而是返回None

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

Perhaps you wanted to do this: 也许您想这样做:

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

To remove the trailing white-space better use str.rstrip : 要删除尾随空格,最好使用str.rstrip

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

help on str.rstrip : 帮助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.

You can write your slice like this (not on the print return value): 您可以这样编写切片(不在打印返回值上):

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

or, you can use join: 或者,您可以使用join:

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

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

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