【每日一题20220714】去除指定的注释文本

:mage:‍ 完成该解决方案,以去除传入的任何一组注释标记之后的所有文本。还应去除行尾的任何空格。

例子:

给定一个输入字符串:

apples, pears # and bananas
grapes
bananas !apples

预期的输出将是:

apples, pears
grapes
bananas

代码会这样调用:

def solution():
    # your code here

assert solution("apples, pears # and bananas\ngrapes\nbananas !apples", ["#", "!"]) == "apples, pears\ngrapes\nbananas"
assert solution("a #b\nc\nd $e f g",  ['#', '$']) == "a\nc\nd"
assert solution(" a #b\nc\nd $e f g",  ['#', '$']) == " a\nc\nd"

题目难度:一般
题目来源:https://www.codewars.com/kata/51c8e37cee245da6b40000bd

import re
from typing import List


def fn(s: str, lis: List[str]) -> str:
    pattern = "[" + "".join(lis) + "]" + ".*"
    lis1 = re.split(pattern, s)
    res = ""
    for s1 in lis1:
        res += s1.rstrip(" ")
    return res

import re
def solution(r,spilt=None):
    par=''.join(spilt)
    return re.sub(fr'[{par}]+.*','',r)
1 个赞
def solution(s,l):
    # your code here
    res = s.split("\n")
    for item in l :
        for i in range(len(res)):
            if item in res[i] :
                res[i] = res[i][:res[i].index(item)]
    return "\n".join([i.rstrip()for i in res])

assert solution("apples, pears # and bananas\ngrapes\nbananas !apples", ["#", "!"]) == "apples, pears\ngrapes\nbananas"
assert solution("a #b\nc\nd $e f g",  ['#', '$']) == "a\nc\nd"
assert solution(" a #b\nc\nd $e f g",  ['#', '$']) == " a\nc\nd"
def solution(a:str,b:list)->str:
    lines=a.split('\n')
    for i in range(len(lines)):
        for j in b:
            if j in lines[i]:
                index=lines[i].index(j)
                lines[i]=lines[i][:index].rstrip()
    return '\n'.join(lines)

assert solution("apples, pears # and bananas\ngrapes\nbananas !apples", ["#", "!"]) == "apples, pears\ngrapes\nbananas"
assert solution("a #b\nc\nd $e f g",  ['#', '$']) == "a\nc\nd"
assert solution(" a #b\nc\nd $e f g",  ['#', '$']) == " a\nc\nd"
import re
def solution(s:str,l:list):
    symbol = ''.join(l)
    pattern = f'\s*[{symbol}].*'  #先获取到正则表达式
    return ''.join(re.split(pattern,s))  # re.split()可以使用正则(多个分割符号)分割字符串