Write a function that accepts an input string consisting of alphabetic characters and removes all the trailing whitespace of the string and returns it without using any .strip() method. For example if:
input_string = " Hello "
then your function should return an output string such as: output_string = " Hello"
这是我的代码:
def Trailing_White_Space (input_str):
count = 0
for i in range (len(input_str) + 1, 0):
if (input_str[i] != ' '):
count = i
break
new_s = input_str[len(input_str):count]
return (new_s)
#Main Program
input_str = " Hello "
result = Trailing_White_Space (input_str)
print (result)
我确信逻辑是正确的。我已经用可能的测试用例试运行了代码。我的代码仍然没有给出任何输出。请帮忙。
最佳答案
这是您遇到问题的主要原因:
input_str[len(input_str):count]
如果切片从len(input_str)
开始,那么您根本无法从中获取任何字符。您只需使用 [:count]
,但您也无法正确获取 count
。
为了从末尾循环,您必须使用范围的第三个参数来减少您的值,因此它必须是
for i in range(len(input_str) - 1, -1, -1):
您需要 -1,每次将值减一。您还希望从 len-1 开始,否则您会得到无效索引,如果您想以 0 结束,则需要传递 -1,因为范围不会到达最终值。
现在您可以正确使用 count
和切片 input_str
:
return input_str[:count]
关于python - 如何删除Python中的尾随空格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35554161/