如何将字符串中的相同字符更改为python中的不同值?

时间:2017-11-13 20:57:56

标签: python

我试图实施一个基本的转换程序,将星标改为<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>")

4 个答案:

答案 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中的imapitertools解决方案:

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>在结果中。