蟒蛇。在字符串中用</b>替换第二个“ **”

时间:2020-07-27 14:00:00

标签: python string

我试图将Markdown字符串解析为HTML格式,并努力寻找一种解决方案,以将**的第二次出现替换为</b>

基本上,我想编写一个将Makdown字符串作为输入和输出HMTL字符串的函数。

输入:** Hello!** everyone! **This should be HTML string**

输出:** Hello!</b> everyone! **This should be HTML string</b>

第二步,我计划使用str.replace()函数,并将其余的**替换为<b>

对于任何建议将不胜感激!

6 个答案:

答案 0 :(得分:2)

我将为“ **”子字符串实现一个计数器(将使它遍历字符串并查找*并检查其旁边是否还有一个),然后执行if(counter%2 == 0)替换。

希望这会有所帮助,这是新手。

答案 1 :(得分:2)

使用markdown库是可行的方法,但是如果您想在没有第三方库的情况下自己执行此操作,那么正则表达式将使您的工作更加轻松。这些允许您查找并替换与模式匹配的文件,以您为例,首先要搜索正则表达式模式

\*\*(.*?)\*\*

星号必须转义,所以这会寻找2个星号

后接括号。圆括号告诉我们我们要捕获其中的内容以供以后参考

然后.*告诉我们匹配不限数量的字符。 .是任何字符,*是无限的。最后的?告诉我们不要贪婪,因此我们会尽快停止。

并替换为

<b> \1 </b>

\1将引用上面括号中的内容。如果还有更多括号,则可以使用\2,然后是\3等来引用下一组括号。

import re

replaced_str = re.compile('\*\*(.*?)\*\*', '<b> \1 </b>', your_string)

或者,您可以搜索第一个**的位置,然后查找下一个**的位置,并使用该信息进行替换。

s = '** Hello!** everyone! **This should be an HTML string**'
while True:
    pos1 = s.find('**')
    pos2 = pos1 + s[pos1+2:].find('**')

    if pos1 >= 0 and pos2 > pos1:
        s = s[:pos1] + '<b>' + s[pos1+2:pos2+2] + '</b>' + s[pos2+4:]
    else:
        break;

print(s)

答案 2 :(得分:1)

这是使用正则表达式的解决方案

import re
text = "** Hello!** everyone! **This should be HTML string**"

p = re.compile(r"\*\*(.*?)\*\*")

result = re.sub(p, r"<b>\1<b/>", text)

"""
result: '<b> Hello!</b> everyone! <b>This should be HTML string</b>'
"""

答案 3 :(得分:1)

计划使用str.replace()

然后,您可以利用此函数接受的可选(第三个)参数-替换次数,方法如下:

txt = '** Hello!** everyone! **This should be HTML string**'
closing = False
while '**' in txt:
    txt = txt.replace('**','</b>' if closing else '<b>',1)
    closing = not closing
print(txt)

输出:

<b> Hello!</b> everyone! <b>This should be HTML string</b>

尽管如此,我建议尽可能使用现成的工具来应对降价。

答案 4 :(得分:0)

如果您是Stackoverflow的新手,我总是建议您从网络上进行研究,并尝试提出一些解决方案,如果您仍然不能这样做,那么您总是可以在这里询问

可以很容易地做到这一点

    import re
    test_str= '** Hello!** everyone! **This should be HTML string**'
    pattern='**'
    res = [i for i in range(len(test_str)) if test_str.startswith(pattern, i)] 
    res
    for i,pos in enumerate(res):    
        if i%2==0:
            test_str = test_str[:pos] + '<b>' + test_str[pos+3:]
        else: 
            test_str = test_str[:pos] + '</b>' + test_str[pos+4:]

答案 5 :(得分:0)

正如法鲁克·伊马莫维奇(Faruk Imamovic)先前提出的那样,我认为这是解决该问题的最佳方法。

opening = True
pos = 0
res = []
while pos < len(text):
    if text[pos] == "*" and pos < len(text)-1 and text[pos+1] == "*":
        res.append('<b>' if opening else '</b>')
        opening = not opening
        pos += 2
    else:
        res.append(text[pos])
        pos += 1
return ''.join(res)