python - 如何删除Python中的尾随空格?

标签 python python-3.x

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/

相关文章:

Python正则表达式,分割参数,忽略引号中的逗号

Python 在 n 处切片列表并获取接下来的 x 个元素?

python - Django - TemplateDoesNotExist 在

python-3.x - tesseract 输出与输入图像不同

python - 如何将导入的txt文件的文件名添加到python中的数据帧

javascript - 使用按钮和 javascript 在 Flask 中设置 python 变量

python - 如何在 Airflow 中的 SLA 上设置时间对象而不是 timedelta?

python - 替换python中的多字节字符

python - 从嵌套字典/json 中删除键

python - 如何覆盖两层深度的类属性?