擅长:python、mysql、java
<p>只需使用<a href="http://docs.python.org/library/stdtypes.html#str.strip" rel="noreferrer">.strip()</a>,它会在拆分时为您删除所有空白,包括制表符和换行符。然后可以使用<a href="http://docs.python.org/library/stdtypes.html#str.splitlines" rel="noreferrer">^{<cd1>}</a>完成拆分:</p>
<pre><code>[s.strip() for s in data_string.splitlines()]
</code></pre>
<p>输出:</p>
<pre><code>>>> [s.strip() for s in data_string.splitlines()]
['Name: John Smith', 'Home: Anytown USA', 'Phone: 555-555-555', 'Other Home: Somewhere Else', 'Notes: Other data', 'Name: Jane Smith', 'Misc: Data with spaces']
</code></pre>
<p>现在甚至可以在<code>:</code>上内联拆分:</p>
<pre><code>>>> [s.strip().split(': ') for s in data_string.splitlines()]
[['Name', 'John Smith'], ['Home', 'Anytown USA'], ['Phone', '555-555-555'], ['Other Home', 'Somewhere Else'], ['Notes', 'Other data'], ['Name', 'Jane Smith'], ['Misc', 'Data with spaces']]
</code></pre>