删除字符串开始及末尾的空白符,并且把数组中间的多个空格(如果有)符转化为1个。

下面python代码里面的第二个和第三个函数都能实现题目的功能,第二个使用了系统的正则库。第一个函数是删除字符串中所有空格。

 

def remove_all_blank(ss):
    '''
    delete all blank in string ss
    :param ss:
    :return:
    '''
    #empty string or None
    if not ss or len(ss) == 0:
        return ''

    letters = list(ss)
    i = 0
    for j in range(len(letters)):
        if letters[j] != ' ':
            letters[i] = letters[j]
            i = i + 1
        else:
            pass
    return ''.join(letters[0:i])

def remove_redundant_blank_with_re(string):
    '''
    remove blank at the beginning and end of string, compress successive blanks into one blank in the middle of string
    :param string:
    :return:
    '''
    string = string.strip()
    import re
    sub_string = re.split('[ ]+', string)
    return ' '.join(sub_string)

def remove_redundant_blank2(string):
    '''
    remove blank at the beginning and end of string, compress successive blanks into one blank in the middle of string
    :param string:
    :return:
    '''
    first = True
    letters = []
    for s in string:
        if s != ' ':
            letters.append(s)
            first = True
        elif s == ' ' and first:
            letters.append(s)
            first = False
        else:
            pass

    #delete blank in front of string
    if letters[0] == ' ':
        if len(letters) > 1:
            letters = letters[1:]
        else:
            return []
    #delete blank at the end of string
    if letters[-1] == ' ':
        del letters[-1]

    return letters

if __name__ == '__main__':
    print(remove_all_blank("    "))
    print(remove_redundant_blank2("   a   "))

 

 

 

 

 

 

 

 

 

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值