简体   繁体   English

如何删除python中的尾随空白?

[英]How to remove the trailing white spaces in python?

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. 编写一个函数,该函数接受由字母字符组成的输入字符串,并删除该字符串的所有结尾空格,并在不使用任何.strip()方法的情况下将其返回。 For example if: 例如,如果:

input_string = " Hello " input_string =“你好”

then your function should return an output string such as: output_string = " Hello" 那么您的函数应该返回输出字符串,例如:output_string =“ Hello”

This is my code: 这是我的代码:

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)

I am certain that the logic is correct. 我确信逻辑是正确的。 I have dry run the code with possible test cases. 我用可能的测试用例试运行了代码。 Still my code doesn't give any output. 我的代码仍然没有给出任何输出。 Please help. 请帮忙。

Here's the main reason you're having trouble: 这是您遇到麻烦的主要原因:

input_str[len(input_str):count]

If the slice starts at len(input_str) then you wont get any characters out of it at all. 如果切片以len(input_str) 开头 ,那么您len(input_str)不会得到任何字符。 You need to only use [:count] , except that you're also not getting count correctly. 您只需要使用[:count] ,除了不能正确count

In order to loop from the end you have to use the third argument for range to decrement your value, so it has to be 为了从头开始循环,您必须对范围使用第三个参数来减小您的值,因此必须

for i in range(len(input_str) - 1, -1, -1):

You want -1, which reduces the value by one each time. 您需要-1,这会使值每次减少一。 You also want to start at len-1 otherwise you get invalid indices, and if you want to end at 0 you need to pass -1, since range doesn't go to the end value. 您还希望从len-1开始,否则会得到无效的索引,并且如果要在0处结束,则需要传递-1,因为range不会达到结束值。

Now you can get use the count and slice input_str properly: 现在您可以正确使用count和slice input_str

return input_str[:count]

In case you want to see a one-liner answer. 如果您想看到单线答案。 This is it: 就是这个:

from string import whitespace as ws
def remove_trailing_whitespace(t):
    return t[:-next(i for i, c in enumerate(t[::-1]) if c not in ws)]

Example: 例:

>>> print '"{}"'.format(remove_trailing_whitespace('  hello  '))  # spaces
"  hello"
>>> print '"{}"'.format(remove_trailing_whitespace('  hello\n'))  # newline
"  hello"
>>> print '"{}"'.format(remove_trailing_whitespace('  hello\t'))  # tab
"  hello"
>>> print '"{}"'.format(remove_trailing_whitespace('  hello \t\n '))  # space, newline, tab
"  hello"

Bonus: all whitespace chars, not just space, and best efficiency. 奖励:所有空格字符,不仅仅是空间,而且效率最高。

Correct the line where you assign new_s variable. 更正分配new_s变量的行。

new_s = input_str[:count+1]

Also, since you're loop needs to be decremented after every iteration. 同样,由于循环,每次迭代后都需要递减。 Replace 0 with -1 . 0替换为-1

for i in range(len(input_str)-1, -1, -1):

EDIT: Refer @InbarRose's answer for a much better alternative. 编辑:请参阅@InbarRose的答案以寻求更好的选择。

Try using re.sub() 尝试使用re.sub()

import re

def remove(my_string):
    new_string = re.sub(r'(.*?\w)([ \t\n\r]*)', r'\1', my_string)
    return(new_string)

my_string = str(input())
modified = remove(my_string)
print(modified)

Explanation: 说明:

re is a module in python for regular expressions. re是python中用于正则表达式的模块。

re.sub(pattern, replacing_pattern, string_to_be_modified) is the syntax. re.sub(pattern, replacing_pattern, string_to_be_modified)是语法。

Here, any character in the square braces ( \\w -> any character, 在这里,方括号中的任何字符( \\w >任何字符, -> space, \\t -> tab, \\n -> newline, \\r -> carriage return) when encountered is replaced by '' (Nothing). ->空格, \\t >制表符, \\n >换行符, \\r >回车符)被替换为'' (无)。 Hence you get a stripped string. 因此,您得到一个剥离的字符串。

Find all the regex matches here 在这里找到所有正则表达式匹配项

range() by default goes up. 默认情况下, range()会上升。 If you want it to go in reverse, you have to set the step explicitly. 如果要使其反向,则必须显式设置步骤。 Also, you don't want to start at len(input_str) + 1. You want to start at len(input_str) - 1. For any iterable, x, x[len(x)] is not defined. 另外,您也不想从len(input_str) + 1开始。您想从len(input_str) -1开始 。对于任何可迭代的对象,未定义x[len(x)] x[len(x) + 1] is even farther off. x[len(x) + 1]更远。 To get the last element, you should use len(input_str) - 1 . 要获取最后一个元素,应使用len(input_str) - 1 Also, if you set the second number to 0 , then the first element will not be evaluated. 同样,如果将第二个数字设置为0 ,则将不评估第一个元素。 The second argument to range() is exclusive , so you should go one number farther than you think you should: range()的第二个参数是Exclusive ,因此您应该比想像的更远一个数:

def Trailing...
    count = 0
    for i in range(len(input_str) - 1, -1, -1):
    ...

Use while loop: 使用while循环:

my_str = ' hello   '
while len(my_str) > 0 and my_str[-1] == ' ':
    my_str = my_str[:-1]

print(my_str) # prints: ' hello'

Your loop is not going through. 您的循环没有通过。 You have to specify that it is decrementing. 您必须指定它在递减。 Below is the working code. 以下是工作代码。

def Trailing_White_Space (input_str):

    count = 0
    for i in range (len(input_str)-1, 0, -1):
        if (input_str[i] != ' '):
            count = i
            break
    slice_index= (len(input_str)-count)-1
    new_s = input_str[0:-1*slice_index]
    return (new_s)

#Main Program
input_str = "    Hello    "
result = Trailing_White_Space (input_str)
print (result)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM