victory的博客

长安一片月,万户捣衣声

0%

python | 去除字符串首尾空格

去除字符串首尾空格

程序使用两种方法去除字符串首尾的空格。

1.strip() rstrip() lstrip()

a = '  welcome to my world  '
print(len(a))
print(len(a.strip()))  # 去掉首尾字符串
print(len(a.lstrip()))  # 去掉首部空格
print(len(a.rstrip()))  # 去掉尾部空格
print(len(a.lstrip().rstrip()))  # 先去掉首部空格再去掉尾部空格

2.递归实现

def trim(s):
    flag = 0
    if s[:1] == ' ':
        s = s[1:]
        flag = 1
    if s[-1:] == ' ':
        s = s[:-1]
        flag = 1
    if flag == 1:
        return trim(s)
    else:
        return s
print(len('  Hello World  '))  # 15
print(len(trim('  Hello World  ')))  # 11

3.while循环实现

def trim(s):
    while True:
        flag = 0
        if s[:1] == ' ':
            s = s[1:]
            flag = 1
        if s[-1:] == ' ':
            s = s[:-1]
            flag = 1
        if flag == 0:
            break
    return s
print(len('  Hello World  '))  # 15
print(len(trim('  Hello World  ')))  # 11