[英]Replace each char in a multi-line string except space and \r \n, how?
[英]Multi-line string on converting to dictionary has \r\n appended to key in dictionary, how to strip \r\n?
下面是用於將多行字符串轉換為字典的代碼。
data = []
header = "Header: JAVA\
Length: 0xa\
Revision: 0x0"
for value in header.split(', '):
if ':' in value:
data.append(map(str.strip, value.split(':', 1)))
獲取輸出為:{Header: JAVA \r\n Length: 0xa \r\n Revision: 0x0 ....}
如何剝離這些 \r\n 並獲得類似 {Header: JAVA Length: 0xa Revision: 0x0 ....} 的輸出
我看到你將數據初始化為一個列表,而你的輸出有 {} 這是一個字典。 因此,我已將您的數據從列表更改為字典。 此外,您應該從“\n”而不是“,”拆分。 以下是我的解決方案:
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
這是輸出:
$ python test.py
{'Header': 'JAVA', 'Length': '0xa', 'Revision': '0x0'}
使用splitlines
和re.split
可以簡化這一點,尤其是與列表推導結合使用時。
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]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.