Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Replace list of items on text

How do I iterate through list_of_items and replace each item from the list like this

for item in list_of_items:
    text.replace(item, ' ' + item)

I just don’t know how to save the resulting text, so that it would contain all the relevant changes if any.

list_of_items = ['PN', 'DESCRIPTION', 'LOCATION', 'CONDITION',
             'RECEIVER#', 'UOM', 'EXP DATE', 'PO', 'CERT SOURCE',
             'REC.DATE', 'MFG', 'BATCH#', 'DOM', 'REMARK', 'LOT#',
             'TAGGED BY', 'Qty', 'NOTES'] 

text = '''
PN: tst SN: 123123
DESCRIPTION: PART
LOCATION: 111 CONDITION: FN
RECEIVER#: 9UOM: EA
EXP DATE: 13.04.2022 PO: P101
CERT SOURCE: wef
REC.DATE:18.04.2022 MFG: efwfe
BATCH# : 1 DOM: 13.04.2022
REMARK: LOT# : 1
TAGGED BY: 
'''

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

If the replacement is working as intended and you just want to "save" the new text, simply reassign the new value back to the text variable

list_of_items = ['PN', 'DESCRIPTION', 'LOCATION', 'CONDITION',
             'RECEIVER#', 'UOM', 'EXP DATE', 'PO', 'CERT SOURCE',
             'REC.DATE', 'MFG', 'BATCH#', 'DOM', 'REMARK', 'LOT#',
             'TAGGED BY', 'Qty', 'NOTES'] 

text = '''
PN: tst SN: 123123
DESCRIPTION: PART
LOCATION: 111 CONDITION: FN
RECEIVER#: 9UOM: EA
EXP DATE: 13.04.2022 PO: P101
CERT SOURCE: wef
REC.DATE:18.04.2022 MFG: efwfe
BATCH# : 1 DOM: 13.04.2022
REMARK: LOT# : 1
TAGGED BY: 
'''

for item in list_of_items:
   text = text.replace(item, ' ' + item)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading