Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/350.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
删除python 3中的尾随空白_Python_For Loop_Python 3.x_Character_Trailing - Fatal编程技术网

删除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)