我试图实施一个基本的转换程序,将星标改为<em>
或</em>
,具体取决于它们是一对中的第一个还是第二个,但不管我做什么我的程序会将所有星标更改为<em>
或</em>
。
line = "*ju*bil*ee*"
star_counter = 0
new_line = line
for character in line:
if character is "*":
star_counter += 1
if star_counter%2 == 0:
new_line = line.replace(character, "</em>")
else:
new_line = line.replace(character, "<em>")
答案 0 :(得分:2)
您已经逐个字符地循环输入字符串,因此只需附加到输出(您打开/关闭em
标记的切换就可以了。)
line = "*ju*bil*ee*"
expected = "<em>ju</em>bil<em>ee</em>"
star_counter = 0
new_line = ""
for character in line:
if character is "*":
star_counter += 1
if star_counter%2 == 0:
new_line += "</em>"
else:
new_line += "<em>"
else:
new_line += character
assert new_line == expected
答案 1 :(得分:0)
使用cycle
中的imap
和itertools
解决方案:
from itertools import cycle, imap
em = iter(cycle(['<em>','</em>']))
def emEm(c):
if c == '*':
return em.next()
else:
return c
line = imap(emEm,"*ju*bil*ee*")
print(''.join(line))
cycle(['<em>','</em>'])
根据需要懒惰地重复<em>
和</em>
emEm
实现了imap imap
执行字符串问题:奇数*会得到一个格式不正确的html - 标签会打开但不会关闭 - 但你可以事先检查一下。
答案 2 :(得分:0)
new_line = "*ju*bil*ee*"
star_counter = 0
for character in new_line:
if character is "*":
if star_counter == 0:
new_line = new_line.replace(character, "<em>", 1)
star_counter=1
else:
new_line = new_line.replace(character, "</em>", 1)
star_counter = 0
print(new_line)
输出
<em>ju</em>bil<em>ee</em>
答案 3 :(得分:0)
您可以使用正则表达式替换来执行此操作。
import re
new_line = re.sub(r'\*([^*]+)\*', r'<em>\1</em>', line)
正则表达式匹配两个*
,其中包含一些非*
个字符,使用捕获组捕获中间文本,然后在<em>
之间替换该捕获组和</em>
在结果中。