循环遍历int的列表,并将字符串中的值替换为

2024-10-03 13:17:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个帐户列表:

account = [79173,84830,86279]

我有一个包含n个信息的字符串,包括一个介于<key_value></key_value>之间的帐户id:

import re

text_msg = """
      <field>
        <field_name>accountinfoid2</field_name>
        <key_value>286249</key_value>
        <target_name>Field2</target_name>
        <target_type>Integer</target_type>
        <target_format />
        <target_length>-1</target_length>
        <target_precision>-1</target_precision>
        <target_decimal_symbol />
        <target_grouping_symbol />
        <target_currency_symbol />
        <target_null_string />
        <target_aggregation_type>-</target_aggregation_type>
      </field>
"""

我需要的是用列表account中的帐户id替换286249

<field>
        <field_name>accountinfoid2</field_name>
        <key_value>79173</key_value>
        <target_name>Field2</target_name>
        <target_type>Integer</target_type>
        <target_format />
        <target_length>-1</target_length>
        <target_precision>-1</target_precision>
        <target_decimal_symbol />
        <target_grouping_symbol />
        <target_currency_symbol />
        <target_null_string />
        <target_aggregation_type>-</target_aggregation_type>
      </field>
      <field>
        <field_name>accountinfoid2</field_name>
        <key_value>84830</key_value>
        <target_name>Field2</target_name>
        <target_type>Integer</target_type>
        <target_format />
        <target_length>-1</target_length>
        <target_precision>-1</target_precision>
        <target_decimal_symbol />
        <target_grouping_symbol />
        <target_currency_symbol />
        <target_null_string />
        <target_aggregation_type>-</target_aggregation_type>
      </field>
<field>
        <field_name>accountinfoid2</field_name>
        <key_value>86279</key_value>
        <target_name>Field2</target_name>
        <target_type>Integer</target_type>
        <target_format />
        <target_length>-1</target_length>
        <target_precision>-1</target_precision>
        <target_decimal_symbol />
        <target_grouping_symbol />
        <target_currency_symbol />
        <target_null_string />
        <target_aggregation_type>-</target_aggregation_type>
      </field>

我试过:

completed_account = []
for i in account:
    temp = re.sub('(?<=<key_value>).*?(?=</key_value>)',i,text_msg,flags=re.DOTALL)
    completed_account.append(temp)
print(completed_account)

得到了错误:

decoding to str: need a bytes-like object, int found

我做错什么了?你知道吗


Tags: keynameformatfieldtargetvaluetypeaccount
1条回答
网友
1楼 · 发布于 2024-10-03 13:17:29

re.sub期望第二个参数(替换)是字符串或函数。你知道吗

尝试将i强制转换为字符串:

completed_account = []
for i in account:
    temp = re.sub('(?<=<key_value>).*?(?=</key_value>)', str(i), text_msg, flags=re.DOTALL)
    completed_account.append(temp)
print(completed_account)

相关问题 更多 >