0

I'm very very new to Python (and programming in general) and I'm trying to figure out how to create a newline at the end of a script.

When I run:

x = 'summary'
print "\nthe election is: %s\n" % x

It returns this in Powershell:

>

the election is: summary

>

However, if I run this:

x = 'summary'
print "\nthe election is: \n", x 

It returns this in Powershell:

>

the election is:
summary
>

In the second example, I can't figure out how to use "\n" to have summary stay on the same line as the sentence "The election is", while adding a newline after it.

All help is greatly appreciated.

Blackacre
  • 23
  • 3
  • Use a format string: `print "\nthe election is: {}\n".format(x)` – zondo Mar 19 '16 at 20:51
  • Take a look at [this](http://stackoverflow.com/a/2962966/5827958) answer. – zondo Mar 19 '16 at 20:53
  • Why are you using a newline if you don't want one? Also what is wrong with using format? – Padraic Cunningham Mar 19 '16 at 20:54
  • I asked my question very poorly. I should have been more clear and simply asked how to get a "new line" between the end of my program being printed in PowerShell and the cursor. T. Silver answered it below by simply typing in "print" on the following line. Thanks to everyone. – Blackacre Mar 19 '16 at 21:12
  • Thanks for the suggestion on the format string Zondo. It definitely accomplishes what I am trying to do. I haven't hit format strings in my book yet, so I wasn't aware I could do that. – Blackacre Mar 19 '16 at 21:18

3 Answers3

0

You can avoid \n altogether:

x = 'summary'
print # new line
print "the election is:", # comma prevents new line
print x
print
T. Silver
  • 372
  • 1
  • 6
  • Why put `print x` on a different line? You could do `print "the election is:", x`. I didn't downvote, but I can understand why one might: this is not at all the easiest way. You could use one of the many solutions in [this](http://stackoverflow.com/a/2962966/5827958) answer. – zondo Mar 19 '16 at 20:56
  • thanks Zondo, I read that post, it's a bit beyond my knowledge at this stage. The problem is that I didn't ask my question very well. – Blackacre Mar 19 '16 at 21:13
0

If you use the print statement like this

print "foo\n", x

then there is no way to get the before the new line symbol. So, as a solution you might want to use another print statement:

x = 'summary'
print "\nthe election is: ", x
print "\n" 
MEVIS3000
  • 521
  • 3
  • 18
  • Thanks. I guess I have a follow up question to this as well: Can I not just put: "print" on the next line, without the "\n" to create a space between the sentence and the cursor? – Blackacre Mar 19 '16 at 21:17
  • True that, just the print statement gives a new line. So, the "\n" is actually redundant – MEVIS3000 Mar 20 '16 at 11:17
0

You can use concatenation with strings using +

x = "summary"
print("\nthe election is: " + x + "\n")
Tony
  • 1,318
  • 1
  • 14
  • 36