python练习二

作者: 一个菜菜的程序员 | 来源:发表于2018-11-26 16:39 被阅读0次

题目:利用切片操作,实现一个trim()函数,去除字符串首尾的空格,注意不要调用str的strip()方法

环境:windows 7+anaconda3 64bit+pycharm

方法一:

def trim(s):

    if s[:1]!=' ' and s[1:]!=' ':

        return s

    elif s[:1]==' ':

        return s[1:]

    else:

        return s[:1]

print(trim(' Hello world!'))

print(trim('Hello world! '))

方法二:

def trim(s):

    for i in range(len(s)):

        if s[0] == ' ':

            s = s[1:]

    for k in range(len(s)):

        if s[-1] == ' ':

            s = s[:-1]

    return s

print(trim(' Hello world!'))

print(trim('Hello world! '))

切片在python中用处很大,可以实现很多循环才能完成的操作。

相关文章

网友评论

    本文标题:python练习二

    本文链接:https://www.haomeiwen.com/subject/saibqqtx.html