Python - Removing \n when using default split()?
<p>I'm working on strings where I'm taking input from the command line. For example, with this input:</p>

<pre><code>format driveName "datahere"
</code></pre>

<p>when I go string.split(), it comes out as:</p>

<pre><code>&gt;&gt;&gt; input.split()
['format, 'driveName', '"datahere"']
</code></pre>

<p>which is what I want.</p>

<p>However, when I specify it to be string.split(" ", 2), I get:</p>

<pre><code>&gt;&gt;&gt; input.split(' ', 2)
['format\n, 'driveName\n', '"datahere"']
</code></pre>

<p>Does anyone know why and how I can resolve this? I thought it could be because I'm creating it on Windows and running on Unix, but the same problem occurs when I use nano in unix.</p>

<p>The third argument (data) could contain newlines, so I'm cautious not to use a sweeping newline remover. </p>

<p>The default <code>str.split</code> targets a number of "whitespace characters", including also tabs and others. If you do <code>str.split(' ')</code>, you tell it to split <em>only</em> on <code>' '</code> (a space). You can get the default behavior by specifying <code>None</code>, as in <code>str.split(None, 2)</code>.</p>

<p>There may be a better way of doing this, depending on what your actual use-case is (your example does not replicate the problem...). As your example output implies newlines as separators, you should consider splitting on them explicitly.</p>

<pre><code>inp = """
format
driveName
datahere
datathere
"""
inp.strip().split('\n', 2)
# ['format', 'driveName', 'datahere\ndatathere']
</code></pre>

<p>This allows you to have spaces (and tabs etc) in the first and second item as well.</p>

python