我有這段文字,我需要將它分成幾行:
text = """
| Post code | Cost, thousands USD |
|----------- ----------------------|
| 33022 | 0.543 |
| 33145 | 9563.214 |
| 33658 | 85.543 |
| 33854 | 0.010 |
| 33698 | 1000000.000 |
"""
期望輸出包含 7 個單獨的行或包含包含一行的七個元素的串列
uj5u.com熱心網友回復:
我的方法是用“\n”拆分這個字串,只參考值所在的行,然后用“|”拆分它們,洗掉額外的空格以將每個專案添加到元組中。
text = """
| Post code | Cost, thousands USD |
|----------- ----------------------|
| 33022 | 0.543 |
| 33145 | 9563.214 |
| 33658 | 85.543 |
| 33854 | 0.010 |
| 33698 | 1000000.000 |
"""
records = []
for i in text.strip().split("\n")[2:]:
row = i[3:-2].split("|")
values = tuple(j.strip() for j in row)
records.append(values)
這樣,記錄將等于元組串列,其中每個值都是一列:
[('3022', '0.543'),
('3145', '9563.214'),
('3658', '85.543'),
('3854', '0.010'),
('3698', '1000000.000')]
如果您想要一個單線解決方案:
records = [tuple(j.strip() for j in i[3:-2].split("|")) for i in text.strip().split("\n")[2:]]
如果你想保留標題:
headers = [tuple(i.strip() for i in text.strip().split("\n")[0][1:-1].split("|"))]
records = headers records
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/533930.html
標籤:Python细绳
