For循环仅更改最后一个值-Python

时间:2020-03-31 16:05:31

标签: python python-3.x

我正在运行一个for循环,但它只是修改最后一个条目的值,而不是所有值。

False
import re
ht = """
    <tr>
        <td>03-31-2020_00.20.02.1135</td>
    </tr>
        <tr>
        <td>03-31-2020_00.20.02.105</td>
    </tr>
    <tr>
        <td>03-28-2020_05.10.01.7068</td>
    </tr>"""

-取得如下输出(只是修改了最后一个条目,而不是所有匹配的整数)-

for i in ht.split():
        if i.startswith("<td>03-31-2020"):
            htm = (ht.replace(i,'<b><font color="#ff0000">'+i+'</font></b>'))
print (htm)

3 个答案:

答案 0 :(得分:1)

您可以使用re库中的re.sub方法将匹配的模式替换为替换模式。

尝试一下:

html = re.sub(r"(<td>03-31-2020.*?</td>)", r'<b><font color="#ff0000">\1</font></b>', ht)
print(html)

输出:

  <tr>
        <b><font color="#ff0000"><td>03-31-2020_00.20.02.1135</td></font></b>
    </tr>
        <tr>
        <b><font color="#ff0000"><td>03-31-2020_00.20.02.105</td></font></b>
    </tr>
    <tr>
        <td>03-28-2020_05.10.01.7068</td>
    </tr>

答案 1 :(得分:0)

您遇到问题的主要原因是,每次更换时,您都会覆盖htm变量。

尝试改写ht变量:

for i in ht.split('\n'): 
    if i.strip().startswith("<td>03-31-2020"):
    ht = ht.replace(i,'<b><font color="#ff0000">'+i+'</font></b>') 
print (ht)

答案 2 :(得分:0)

在每个循环中,您将变量htm替换为新的替换子字符串,因此您只会看到最后一次匹配的结果。 您宁愿做的就是将替换后的值保存在for循环外的变量中,以免丢失结果

import re
ht = """
    <tr>
        <td>03-31-2020_00.20.02.1135</td>
    </tr>
        <tr>
        <td>03-31-2020_00.20.02.105</td>
    </tr>
    <tr>
        <td>03-28-2020_05.10.01.7068</td>
    </tr>"""

htm = ""
for i in ht.split():
    if i.startswith("<td>03-31-2020"):
        htm += '<b><font color="#ff0000">'+i+'</font></b>' + "\n"
    else:
        htm += i + "\n"
print("htm", htm)

尽管如此,我还是建议使用正则表达式来匹配和替换字符串,使代码更简洁。

相关问题