ForeverLearning ForeverLearning - 1 year ago 105
Python Question

Python - Removing \n when using default split()?

I'm working on strings where I'm taking input from the command line. For example, with this input:

format driveName "datahere"

when I go string.split(), it comes out as:

>>> input.split()
['format, 'driveName', '"datahere"']

which is what I want.

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

>>> input.split(' ', 2)
['format\n, 'driveName\n', '"datahere"']

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.

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

Answer Source

Use None to get the default whitespace splitting behaviour with a limit:

input.split(None, 2)

This leaves the whitespace at the end of input() untouched.

Or you could strip the values afterwards; this removes whitespace from the start and end, not the middle, of each resulting string, just like input.split() would:

[v.strip() for v in input.split(' ', 2)]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download