How do I make spaces between paragraphs in my Python script? - python

I'm making a game in Python (text only) but it gets confusing when people play it because there is no space between the paragraphs, so it looks like this:
'You step outside and feel the wind on your face.'
'Which direction do you turn?'
But I would like it to look like this:
'You step outside and feel the breeze on your face'
'What do you do next'?
Here's my code:
print 'You step outside and feel the cool breeze on your face.'
what = raw_input ('What do you do next ')
Thanks!

Print a newline character.
print("\n")
Or:
print("An angry-looking dwarf throws an axe at you.\nYou die.\n")

You have a few solutions:
The simpler one would be to use a print statement between your lines, which, used alone, prints a line feed.
Alternatively, you could you end the string you're printing with a '\n' character, which will cause a line feed, or you could start your input with the same character.

print('\v')
vertical tab for vertical space.

Related

How to find exactly "\n" in Python IDLE replace dialog?

I'm a begginer in Python and one of the first codes I've made it's an RPG, so there's a lot of texts in strings being printed. Before I learned how to "word wrap", I used to test every string and put an "\n" in the right places, so it could be better to read the history in the console.
But now I don't need those "\n" anymore, and it's been really laborious to replace each one of them using the Replace Dialog of Python IDLE. One of the problems is that I want to ignore double new lines ("\n\n"), because they do make the texts more presentable.
So if I just search "\n" he finds it, but I want to ignore all the "\n\n".
I tried using the "Regular expression" option and did a research with regex but with no success, since I'm completly new in this area. Tried some things like "^\n$" because, if I understood it right, the ^ and the $ delimit the search to what's between them.
I think it's clear what I need, but will write an example anyways:
print("Here's the narrator telling some things to the player. Of course I could do some things but\nnow it's time to ask for help!\n\nProbably it's a simple thing, but it's been lots of time in research and no\nsuccess...")
I want to find and replace those two "\n" with one empty space (" ") and totally ignore the "\n\n".
Can you guys help? Thanks in advance.
You need
re.sub(r'(?<!\n)\n(?!\n)', ' ', text)
See the regex demo.
Details
(?<!\n) - no newline allowed immediately on the left
\n - a newline
(?!\n) - no newline allowed immediately on the right
See Python demo:
import re
text = "Here's the narrator telling some things to the player. Of course I could do some things but\nnow it's time to ask for help!\n\nProbably it's a simple thing, but it's been lots of time in research and no\nsuccess..."
print(re.sub(r'(?<!\n)\n(?!\n)', ' ', text))
Output:
Here's the narrator telling some things to the player. Of course I could do some things but now it's time to ask for help!
Probably it's a simple thing, but it's been lots of time in research and no success...

How can you print a variable in quotation marks?

favoriteword = input('Enter your word: ')
print('What is your favorite word?',favoriteword)
print(favoriteword,favoriteword,favoriteword,favoriteword,favoriteword,favoriteword,favoriteword,favoriteword,favoriteword,favoriteword,favoriteword,favoriteword)
print(favoriteword, 'does not even sound like a word anymore.')
How can I make it so that in line 4 it comes out as "___" does not even sound like a word anymore." If I put it as this below it doesn't work.
print('"favoriteword"', 'does not even sound like a word anymore.')
Also if I put line 2 into a loop how would I print it so that it prints on a single line?
for i in range(12):
print(favoriteword)
In Python 2.6 or above, you can use string.format:
print('"{}" does not even sound like a word anymore.'.format(favoriteword))
In lower versions, Ketzak's method will work.
To print multiple times on a single line, you want to prevent print from appending a newline.
In Python 3, use the end argument:
for i in range(12):
print(favoriteword, end='')
print('') # for newline
or in lower versions:
import sys
for i in range(12):
sys.stdout.write(favoriteword)
print('')
Use the Python interpolation operator if you can guarantee favoriteword will always be a string:
print('"%s" does not even sound like a word anymore.' % favoriteword)
In python >= 3.6, you can use "f-string":
print(f'"{favoriteword}" does not even sound like a word anymore.')
See this link for more information about it.

Replacing more than one line in the console in python

I'm writing a program in python and I'd like to replace more than one line in the console with new text.
For example if I have 3 sentences printed to the console with:
print("Hello World!")
print("How are you!")
print("What's going on?")
Where each on is on a different line (and so has an \n).
How do I go about replacing all of this text when it displays in the console? I can't us \r in this situation due to the \n.
This is kind of an old post, but I came across it and worked out a solution as well. Added a timer, because otherwise the print statements bury each other and you'll only be able to read the last one. I'm on python 2.7:
import os
import time
os.system("printf 'Hello World!'")
time.sleep(1)
os.system("printf '\rHow are you?!'")
time.sleep(1.5)
os.system("printf '\rWhats going on?'")
os.system("echo ")
A simple fix would be to simply change the end separator for printing your strings. you can specify how you want the print function to separate calls with the end argument
print("hello world!", end="")
print("\rhello world again!")
In this case, we're setting the separator to "", which is nothing. So printing the next strings starts on the same line thus \r can be used. Compiling that gives you hello world again! on one line.

Problems with Syntax and indentation errors

I'm going through a Book which, at this point in the book, requires me to make a small videogame that calls functions, uses if's, while's -- essentially all the things covered in the book so far. But, I get this error in this part of my code:
Code edited, get a new error.
File "ex35_study.py", line 24
third_scenario_code()
IndentationError: unindent does not match any outer indentation level
Here is my code:
options_thirdscenario_actions = ['Examine the door', 'Try to force it']
def third_scenario_code():
print "Let me try to crack this thing up, says Lars as he starts to type in the panel. You hear the sounds of the fight out there, there's not much time left. "
print "After receiving several commands a window with a code pop ups. "
print codefile.read()
def third_scenario():
print "You two get out of the cell and approach to the exit, a long corridor is ahead of you, flashing red lights indicate an state of emergency, you must evacuate."
print "As soon as you two approach to the door, it closes"
print "Crap it must be the emergency system, we have been detected"
next = raw_input("What do you do> ")
if next == 'Examine the door':
print "A small panel comes out, requires to enter a code of words"
third_scenario_code()
elif next == 'Try to force it':
print "You try to force the door with no result"
print options_thirdscenario_actions
next2 = raw_input("What else do you do> " )
if next2 = 'Examine the door'
third_scenario_code()
else:
print "You already did that"
I am getting a similar error on the whole program and I suspect it has something to do with indentation, but I have tried every suggestion I see in google with no fruitful result. thanks in advance.
You are missing colons after the one of if conditions and need to line things that are the same scope up, i.e. the print after the function call but you may also be mixing spaces and tabs. It is recommended to always use 4 spaces rather than tabs and most programming editors can be set up for this.
I would also suggest getting hold of pylint and using it. It will help you spot a lot of potential errors and will help you to develop good habits.
Its because of the indentation of third_scenario_code() you need to write it under the print .
change the following :
if next == 'Examine the door':
print "A small panel comes out, requires to enter a code of words"
third_scenario_code()
to :
if next == 'Examine the door':
print "A small panel comes out, requires to enter a code of words"
third_scenario_code()

Deleting already printed in Python

For practice, I'm trying to do some stuff in Python. I've decided to make a simple hangman game - I'm not making a GUI. The game would start with a simple input(). Now, I'd like next line to, beside asking for input, to delete the hidden word. I've tried using \b (backspace character), but it's not working. Something like:
word = input("Your word: ")
for i in range(len(word) + 12):
print("\b")
Now, printing the backlash character is supposed to delete the input and "Your word", but it isn't doing anything. If I do this in IDLE I get squares, and I get nothing if I open it by clicking.
How to accomplish this? I'm afraid I wasn't too clear with my question, but I hope you'll see what I meant. :)
\b does not erase the character before the cursor, it simply moves the cursor left one column. If you want text entry without echoing the characters then look at getpass.
I assume the player entering the word wants to be sure they've entered it correctly so you probably want to display the word as they're typing it right?
How about printing enough \ns to move it off the screen when they're done or issue a clear screen command?
You mentioned this was a simple game so a simple solution seems fitting.
[Edit] Here's a simple routine to clear the console on just about any platform (taken from here):
def clearscreen(numlines=100):
"""Clear the console.
numlines is an optional argument used only as a fall-back.
"""
import os
if os.name == "posix":
# Unix/Linux/MacOS/BSD/etc
os.system('clear')
elif os.name in ("nt", "dos", "ce"):
# DOS/Windows
os.system('CLS')
else:
# Fallback for other operating systems.
print '\n' * numlines
word = raw_input("Your word: ")
import sys
sys.stdout.write("\x1b[1A" + 25*" " + "\n")
This will replace the last line printed with 25 spaces.
I think part of your problem is that input is echoing the Enter that terminates your word entry. Your backspaces are on another line, and I don't think they'll back up to the previous line. I seem to recall a SO question about how to prevent that, but I can't find it just now.
Also, I believe print, by default, will output a newline on each call, so each backspace would be on its own line. You can change this by using an end='' argument.
Edit: I found the question I was thinking of, but it doesn't look like there's any help there. You can look at it if you like: Python input that ends without showing a newline

Categories