删除python 3中的尾随空白
我做的程序有点麻烦。我让它显示一个菱形,但我有一个问题,这是我的代码:删除python 3中的尾随空白,python,for-loop,python-3.x,character,trailing,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 + " " + "* " *
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'
>>> 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.
有关str.rstrip的帮助信息:
>>> "foo ".rstrip()
'foo'
>>> 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.
您可以这样编写切片(不在打印返回值上): 或者,您可以使用“加入”:
' '.join(['*']*b)
首先:
i=i+1
在for
循环中是非常奇怪的。为什么要更改循环中的迭代变量?@gefei之所以这样做,是因为python循环从0点开始,我需要它从1点开始。在打印返回值中插入您的片段。输入字符串。多亏了你的输入。我照阿什维尼说的做了,它成功了!谢谢大家!@用户2655778您需要范围(a-1)
。