[英]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.