简体   繁体   English

如何在不使用strip()函数的情况下删除或剥离空格?

[英]How to remove or strip off white spaces without using strip() function?

Write a function that accepts an input string consisting of alphabetic characters and removes all the leading whitespace of the string and returns it without using .strip(). 编写一个函数,该函数接受由字母字符组成的输入字符串,并删除该字符串的所有前导空格,并在不使用.strip()的情况下将其返回。 For example if: 例如,如果:

input_string = " Hello " input_string =“你好”

then your function should return a string such as: 那么您的函数应该返回一个字符串,例如:

output_string = "Hello " output_string =“你好”

The below is my program for removing white spaces without using strip: 下面是我不使用strip删除空格的程序:

def Leading_White_Space (input_str):
    length = len(input_str)
    i = 0
    while (length):
        if(input_str[i] == " "):
            input_str.remove()
        i =+ 1
        length -= 1


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

I chose the remove function as it would be easy to get rid off the white spaces before the string 'Hello'. 我选择了remove函数,因为它很容易摆脱字符串“ Hello”之前的空白。 Also the program tells to just eliminate the white spaces before the actual string. 该程序还指示仅消除实际字符串之前的空格。 By my logic I suppose it not only eliminates the leading but trailing white spaces too. 根据我的逻辑,我认为它不仅消除了前导空格,而且消除了尾随空格。 Any help would be appreciated. 任何帮助,将不胜感激。

You can loop over the characters of the string and stop when you reach a non-space one. 您可以遍历字符串的字符,并在到达非空格字符时停止。 Here is one solution : 这是一种解决方案:

def Leading_White_Space(input_str):
  for i, c in enumerate(input_str):
    if c != ' ':
      return input_str[i:]

Edit : @PM 2Ring mentionned a good point. 编辑 :@PM 2Ring提到了一个好点。 If you want to handle all types of types of whitespaces ( eg \\t,\\n,\\r), you need to use isspace() , so a correct solution could be : 如果要处理所有类型的空格( 例如 \\ t,\\ n,\\ r),则需要使用isspace() ,因此正确的解决方案可能是:

def Leading_White_Space(input_str):
  for i, c in enumerate(input_str):
    if not c.isspace():
      return input_str[i:]

Here's another way to strip the leading whitespace, that actually strips all leading whitespace, not just the ' ' space char. 这是剥离前导空格的另一种方法,实际上是剥离所有前导空格,而不仅仅是' '空格字符。 There's no need to bother tracking the index of the characters in the string, we just need a flag to let us know when to stop checking for whitespace. 无需费心跟踪字符串中字符的索引,我们只需要一个标志让我们知道何时停止检查空白。

def my_lstrip(input_str):
    leading = True
    for ch in input_str:
        if leading:
            # All the chars read so far have been whitespace
            if not ch.isspace():
                # The leading whitespace is finished
                leading = False
                # Start saving chars
                result = ch
        else:
            # We're past the whitespace, copy everything
            result += ch
    return result

# test
input_str = " \n \t Hello    "
result = my_lstrip(input_str)
print(repr(result))

output 输出

'Hello    '

There are various other ways to do this. 还有其他多种方法可以执行此操作。 Of course, in a real program you'd simply use the string .lstrip method, but here are a couple of cute ways to do it using an iterator: 当然,在实际程序中,您只需要使用字符串.lstrip方法,但是这里有一些使用迭代器的可爱方法:

def my_lstrip(input_str):
    it = iter(input_str)
    for ch in it:
        if not ch.isspace():
            break
    return ch + ''.join(it)

and

def my_lstrip(input_str):
    it = iter(input_str)
    ch = next(it)
    while ch.isspace():
        ch = next(it)
    return ch + ''.join(it)

Use re.sub 使用re.sub

>>> input_string = " Hello "
>>> re.sub(r'^\s+', '', input_string)
'Hello '

or 要么

>>> def remove_space(s):
    ind = 0
    for i,j in enumerate(s):
        if j != ' ':
            ind = i
            break
    return s[ind:]

>>> remove_space(input_string)
'Hello '
>>> 

Just to be thorough and without using other modules, we can also specify which whitespace to remove (leading, trailing, both or all), including tab and new line characters. 只是为了透彻而又不使用其他模块,我们还可以指定要删除的空格(前导,尾随,全部或全部),包括制表符和换行符。 The code I used (which is, for obvious reasons, less compact than other answers) is as follows and makes use of slicing: 我使用的代码(出于明显的原因,其紧凑性不如其他答案)如下,并使用了切片:

def no_ws(string,which='left'):
    """
    Which takes the value of 'left'/'right'/'both'/'all' to remove relevant 
    whitespace.
    """
    remove_chars = (' ','\n','\t')
    first_char = 0; last_char = 0

    if which in ['left','both']:
        for idx,letter in enumerate(string):
            if not first_char and letter not in remove_chars:
                first_char = idx
                break
        if which == 'left':
            return string[first_char:]

    if which in ['right','both']:
        for idx,letter in enumerate(string[::-1]):
            if not last_char and letter not in remove_chars:
                last_char = -(idx + 1)
                break
        return string[first_char:last_char+1]

    if which == 'all':
        return ''.join([s for s in string if s not in remove_chars])

you can use itertools.dropwhile to remove all particualar characters from the start of you string like this 您可以使用itertools.dropwhile从这样的字符串开头删除所有特殊字符

import itertools

def my_lstrip(input_str,remove=" \n\t"):
    return "".join( itertools.dropwhile(lambda x:x in remove,input_str))

to make it more flexible, I add an additional argument called remove, they represent the characters to remove from the string, with a default value of " \\n\\t" , then with dropwhile it will ignore all characters that are in remove, to check this I use a lambda function (that is a practical form of write short anonymous functions) 为了使其更加灵活,我添加了一个名为remove的附加参数,它们表示要从字符串中删除的字符,默认值为" \\n\\t" ,然后使用dropwhile它将忽略所有处于删除状态的字符,以检查一下我使用了lambda函数(这是编写简短匿名函数的一种实用形式)

here a few tests 这里有一些测试

>>> my_lstrip(" \n \t Hello    ")
'Hello    '
>>> my_lstrip("   Hello    ")
'Hello    '
>>> my_lstrip(" \n \t Hello    ")
'Hello    '
>>> my_lstrip("---   Hello    ","-")
'   Hello    '
>>> my_lstrip("---   Hello    ","- ")
'Hello    '
>>> my_lstrip("- - - Hello    ","- ")
'Hello    '
>>> 

the previous function is equivalent to 以前的功能等效于

def my_lstrip(input_str,remove=" \n\t"):
    i=0
    for i,x in enumerate(input_str):
        if x not in remove:
            break
    return input_str[i:]

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

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