Strip Comments (Codewars 4kyu Python)

题目:

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.

Example:

Given an input string of:

apples, pears # and bananas
grapes
bananas !apples
The output expected would be:

apples, pears
grapes
bananas
The code would be called like so:

result = solution("apples, pears # and bananas\ngrapes\nbananas !apples", ["#", "!"])
# result should == "apples, pears\ngrapes\nbananas"

我的思路:

可以先把string根据 “\n” 分割成每一行的句子,每一行分别去掉maker后的内容,并且检查maker前的内容,如果末尾有多余空格要去掉。

我的解答:

def solution(string,markers):
    s = string.split("\n")
    result = ""
    for i in s:
        trimmed = ""
        for j in i:
            if j not in markers:
                trimmed += j
            else:
                break
        trimmed = trimmed.rstrip()
        result = result + trimmed + "\n"
    return result[:-1]

Most Clever:

做完题目看一下题后投票clever最多的答案:

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)

其中主要语句:

v.split(s)[0].rstrip()

就是用maker把parts里的每个分割成小段,取其中第一个小段,然后去掉右边多余的空格。

总结:

思路基本一致,Most Clever中用maker把parts里的每个分割成小段,取其中第一个小段,比我的检查每行,逐位获取,遇到maker结束,要灵活便捷一些。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值