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

Multi-line string on converting to dictionary has \r\n appended to key in dictionary, how to strip \r\n?

Below is the code used to convert multi-line string to dictionary.

data = []
header = "Header: JAVA\
          Length: 0xa\
          Revision: 0x0"
for value in header.split(', '):
    if ':' in value:
        data.append(map(str.strip, value.split(':', 1)))

Getting output as : {Header: JAVA \r\nLength: 0xa \r\nRevision: 0x0 ….}

How to strip of these \r\n and get output like {Header: JAVA Length: 0xa Revision: 0x0 ….}

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 :

I see that you initialized data as a list whereas your output has {} which is a dict. Therefore I have changed your data from a list to a dict. Also, you should be splitting from "\n" instead of ",". Below is my solution:

data = {}
header = "Header: JAVA\r\nLength: 0xa\r\nRevision: 0x0"
for line in header.split("\n"):
    if len(line) > 0 and len(line.split(":")) > 1:
        key, value = line.split(":")
        key = key.strip()
        value = value.strip()
        data[key] = value

print(data) # for visualization

Here is the output:

$ python test.py                                   
{'Header': 'JAVA', 'Length': '0xa', 'Revision': '0x0'}  
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