【codewars】Strip Comments

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/lluozh2015/article/details/79050861

instruction

Complete the solution so that it strips all text that follows any of a set of comment markers passed in. Any whitespace at the end of the line should also be stripped out.

Examples:
这里写图片描述

my solution

def solution(string,markers):
    #your code here
    for marker in markers:
        string = string.split("\n")
        sArr = []
        for s in string:
            str1 = s.split(marker)
            sArr.append(str1[0].strip())
        strP = ""
        n = 0
        for p in sArr:
            if n==0:
                strP = strP + p
            else:
                strP = strP + "\n" + p
            n+=1
        string = strP
    return string

best solution from others

def solution(string,markers):
    parts = string.split('\n')
    for s in markers:
        parts = [v.split(s)[0].rstrip() for v in parts]
    return '\n'.join(parts)

escape方法

re.escape(pattern) 可以对字符串中所有可能被解释为正则运算符的字符进行转义的应用函数

    a = escape("sss.#ssos?")
    print(a)

>>> sss\.\#ssos\?
    markers = ["#", "!"]
    pattern = "[" + escape("".join(markers)) + "]"
    print(pattern)

>>> [\#\!]

rstrip方法

删除 string 字符串末尾的指定字符(默认为空格)

str.rstrip([chars])

chars - 指定删除的字符(默认为空格)

返回删除 string 字符串末尾的指定字符后生成的新字符串

str = "     this is string example....wow!!!     "
print (str.rstrip())

>>>      this is string example....wow!!!
str = "*****this is string example....wow!!!*****"
print (str.rstrip('*'))

>>> *****this is string example....wow!!!

猜你喜欢

转载自blog.csdn.net/lluozh2015/article/details/79050861
今日推荐