+ 1
New line in python
I'm curious. I want to make a new line in my output, but I want to use a single line in my script to do it. I know \n is involved, but I don't know how to use it. Example: I want the output to be: 2 5 I tried the script, https://code.sololearn.com/cVzbrXH1g9Jq/?ref=app but it produced the output, 2 5 (with a space before the 5) I also tried using + instead of , but it gave me an error message. Thank you for your answer!!
5 Answers
+ 7
Using print() with many parameters (comma separated ',') will concatenate each separated by a space, with the advantage of casting type automatically, as in the other hand, '+' operator with string accept only strings to be concatenated... So, you'll get an error if you try to do:
2+'test'+5
To fix it, you need to explicitly cast (convert) the non-string types in string:
str(2)+'test'+str(5)
... will work, without adding space beetween each operand of the string 'addition'. And so, to get your expected result, you must write:
print(str(2)+'\n'+str(5))
+ 3
@Bogdan Sass: you're right, but the explanation would be less clear (as you do implicite litteral string casting by putting digits inside quotes :P)... and asker would be no more advanced in others circumstances, as if to the question: write a program to print this:
#
##
###
####
... you will answer: a simple print(''#\n##\n###\n####") would have worked fine (or worst, using triple quote multilines string) ^^ The generic case is the thing to be explained, even if the question come from a specific one ;)
0
You could also try using string formatting.
x = 2
y = 5
print("{0}\n{1}".format(x, y))
0
@visph - in this particular case, there was no need for casting to string. A simple
print("2\n5")
would have worked just fine :)
0
You can use :
print ('2', '\n', '5')
it works.