A couple of clarifications regarding this two points of your question
I am trying to pass a string with spaces and newlines
Is it possible to pass this as an arguement and have the output within the python appear as:
When you call your script with python main.py "5 2\n 3 3 2\n 1 1 2"
you are not passing actual newline characters.
This is why you get \\n
in your string, Python is escaping those \n
since otherwise it would mean that your string does have newline chars.
You are confusing the representation of the string and the string itself. Check this question about repr
vs str
.
When printing the string alone it is printed nicely, but when printing the list the escaped characters are shown, which explains why you get different results.
When you do:
input_split = info_input.split(sep='\n')
print(input_split)
you are not actually splitting your string, since you string does not contain newline characters (\n
), it contains escaped newline characters (\\n
).
If you actually want to split your string in newlines you could do:
input_split = info_input.split(sep='\\n')
print(input_split)
which outputs ['5 2', ' 3 3 2', ' 1 1 2']
.
That said, if your goal is to have actual newline characters in your program you can replace the escaped newlines with newlines:
import sys
info_input = sys.argv[1]
info_input_with_escaped_newlines = info_input
print("info_input_with_escaped_newlines as string", info_input_with_escaped_newlines)
print("info_input_with_escaped_newlines as list", [info_input_with_escaped_newlines])
info_input_with_newlines = info_input.replace('\\n', '\n')
print("info_input_with_newlines as string", info_input_with_newlines)
print("info_input_with_newlines as list", [info_input_with_newlines])
which outputs
> python as.py "5 2\n 3 3 2\n 1 1 2"
info_input_with_escaped_newlines as string 5 2\n 3 3 2\n 1 1 2
info_input_with_escaped_newlines as list ['5 2\\n 3 3 2\\n 1 1 2']
info_input_with_newlines as string 5 2
3 3 2
1 1 2
info_input_with_newlines as list ['5 2\n 3 3 2\n 1 1 2']
Notice how now split
does split the string:
import sys
info_input = sys.argv[1].replace('\\n', '\n').split(sep='\n')
print(info_input)
which outputs:
python as.py "5 2\n 3 3 2\n 1 1 2"
['5 2', ' 3 3 2', ' 1 1 2']