python将字符串中的每秒“**”替换为
我正试图将一个降价字符串解析为HTML格式,并努力找到一个解决方案,以将**的每一秒都替换为 基本上,我想写一个函数,它将获得一个合成字符串作为输入和输出HMTL字符串 输入:**你好!**各位!**这应该是HTML字符串** 输出:**你好!各位!**这应该是HTML字符串 在第二步中,我计划使用str.replace函数并将剩余的**替换为python将字符串中的每秒“**”替换为,python,string,Python,String,我正试图将一个降价字符串解析为HTML格式,并努力找到一个解决方案,以将**的每一秒都替换为 基本上,我想写一个函数,它将获得一个合成字符串作为输入和输出HMTL字符串 输入:**你好!**各位!**这应该是HTML字符串** 输出:**你好!各位!**这应该是HTML字符串 在第二步中,我计划使用str.replace函数并将剩余的**替换为 如果您有任何建议,我将不胜感激 这里有一个使用正则表达式的解决方案 进口稀土 text=**你好!**各位!**这应该是HTML字符串** p=re.c
如果您有任何建议,我将不胜感激 这里有一个使用正则表达式的解决方案 进口稀土 text=**你好!**各位!**这应该是HTML字符串** p=re.compiler\*\*.*\*\* 结果=re.subp,r\1,文本 结果:“你好!每个人这应该是HTML字符串'
我将为**子字符串实现一个计数器,使其遍历字符串并查找*并检查旁边是否还有一个,然后ifcounter%2==0替换
希望这能有所帮助,我是新来的。使用降价库是一种方法,但是如果您希望自己在没有第三方库的情况下完成这项工作,那么正则表达式将使您的工作更轻松。这些允许您查找和替换与模式匹配的对象,在您的情况下,您需要从搜索正则表达式模式开始 \*\**\*\* Asteriks必须被转义,因此这将查找2个Asteriks 然后是一个附加组。插入组告诉我们,我们希望捕获其中的内容,以供以后参考 然后,.*告诉我们匹配无限数量的字符。是任意字符,并且*是无限的。这个最后告诉我们不要贪心,所以我们尽快停下来 并将其替换为 \1 \1将引用上面括号中的内容。如果有更多的括号,您将使用\2引用下一组括号,然后使用\3,依此类推 计划使用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>
尽管如此,我还是建议尽可能使用现成的工具来处理降价问题。鉴于您是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:]
正如法鲁克·伊马莫维奇早些时候提出的那样,我认为这里是问题的最佳解决方案
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)
您可以用于大多数文本格式之间的转换:pandoc-standalone-o website.html input.md谢谢!我开始了解re.sub的工作原理。我想买一个降价库,但我只需要这个功能,我想尝试自己实现它。设置一个关闭计数器的好主意!谢谢你的主意!我认为这是最理想的解决方案,只需要读取字符串一次。嗨!是的,我还是新来的。我首先寻找解决方案,但找不到任何适合我的。谢谢你的建议!
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:]
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)