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

Time:06-04

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 ....}

CodePudding user response:

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'}  

CodePudding user response:

Using splitlines and re.split you can simplify this, especially when combined with a list comprehension.

header = """Header: JAVA
          Length: 0xa
          Revision: 0x0"""

data = [[part.strip() for part in re.split(r'\s*\:\s*', line, 1)] 
          for line in header.splitlines()  
          if ':' in line]
  • Related