首页 > 解决方案 > 在 Python 中将字符串解析为不同的格式

问题描述

我有一个文本文档,我需要在数组中的关键字之前添加两个 @ 符号。

示例文本和数组:

str ="This is a sample text document which consists of all demographic information of employee here is the value you may need,name: George employee_id:14296blood_group:b positive this is the blood group of the employeeage:32"

arr=['name','employee_id','blood_group','age']

所需文字:

str ="This is a sample text document which consists of all demographic information of employee here is the value you may need, @@name: George @@employee_id:14296 @@blood_group:b positive this is the blood group of the employee @@age:32"

标签: pythonpython-3.x

解决方案


只需使用该replace功能

str ="This is a sample text document which consists of all demographic information of employee here is the value you may need,name: George employee_id:14296blood_group:b positive this is the blood group of the employeeage:32"
arr = ['name','employee_id','blood_group','age']

for w in arr:
    str = str.replace(w, f'@@{w}')
print(str)

推荐阅读