Very new to python, so ignorance may be shown. (Python 3.10, Windows 10)
I have a simple code that tosses a coin. I want to underline the 'y' and 'n' in "yes" and "no" within this sentence: Do you want to flip another coin? yes or no.
I was able to make it work properly in IDLE, but it doesn't work properly when running in windows. The underline positions shifts to the left in Windows. I assume this is an issue in Windows, but can it be fixed? I'm simply double clicking the python file to run it in Windows, so maybe this is an incorrect way of doing it?
Here is the code for the sentence:
Yes = ('''es''')
No = ('''o''')
print('Do you want to flip another coin? ' + '\u0332y'+Yes + ' or' + ' \u0332n'+No)
Thanks for the help.
I have the solution,
follow the below code,
from prompt_toolkit import print_formatted_text, HTML
print_formatted_text('Do you want to flip another coin? ',HTML('<u>y</u>es'),'or',HTML('<u>n</u>o'))
Related
I want to receive some information from a user in a next way:
My score is of 10 - is already printed
Between 'is' and 'of' there is an empty place for user's input so he doesn't enter his information at the end( if using simple input() ) but in the middle. While user is entering some information it appears between 'is' and 'of'
Is there any possible way to do it?
One way to get something close to what you want is if you terminal supports ANSI escape codes:
x = input("My score is \x1b[s of 10\x1b[u")
\x1b is the escape character. Neither escape character is dipsplayed on the screen; instead, they introduce byte sequences that the terminal interprets as an instruction of some kind. ESC[s tells the terminal to remember where the cursor is at the moment. ESC[u tells the terminal to move the cursor to the last-remembered position.
(The rectangle is the cursor in an unfocused window.)
Using a library that abstracts away the exact terminal you are using is preferable, but this gives you an idea of how such libraries interact with your terminal: it's all just bytes written to standard output.
If you use console then consider importing curses library. It works on both linux and windows. Download it for windows from http://www.lfd.uci.edu/~gohlke/pythonlibs/#curses
With this library you have a total control over console. Here is the answer to your question.
How to input a word in ncurses screen?
This question already has answers here:
How do I print colored text to the terminal?
(64 answers)
Closed 9 years ago.
I'm looking for a way to change the color of the text output from my python scripts as it runs. The basic idea is something like this:
if (Data < LowerLimit):
print "Failed" # Output Failed as Red Text
elif (Data > UpperLimit):
print "Failed" # Red Color
else:
print "Passed" # Blue Color
The scripts are being used on windows machines for quick data analysis.
Or about the best module I have found
http://pypi.python.org/pypi/colorama
This is extremely simple! Rather than importing odd modules for python or trying long commands you can take advantage of windows OS commands.
In windows, commands exist to change the command prompt text color. You can use this in python by starting with a: import os
Next you need to have a line changing the text color, place it were you want in your code.
os.system('color 4')
You can figure out the other colors by starting cmd.exe and typing color help.
The good part? Thats all their is to it, to simple lines of code.
-Day
Try to look at the following link: Python | change text color in shell
Or read here: http://bytes.com/topic/python/answers/21877-coloring-print-lines
In general solution is to use ANSI codes while printing your string.
There is a solution that performs exactly what you need.
Been looking into this for a while and not got any satisfactory answers, however...
1) ANSI escape sequences do work in a terminal on Linux
2) if you can tolerate a limited set of colo(u)rs try this:
print("hello", end=''); print("error", end='', file=sys.stderr); print("goodbye")
In idle "hello" and "goodbye" are in blue and "error" is in red.
Not fantastic, but good enough for now, and easy!
In IDLE, say i want to write the following in TWO lines:
x = 3
print x**5
but when i type x = 3 and press enter, it executes the assignment. How to let it execute AFTER two lines are all typed in?
having read first pages of Python tutorial but no answer to this "funny" question...
Use the Ctrl-J key sequence instead of the Enter key to get a plain newline plus indentation without having IDLE start interpreting your code.
You can find other key sequences that make IDLE easier to use for this type of learning under the Options->Configure IDLE menu.
End lines with ;\:
>>> x=3;\
... print x**5
243
>>>
after every line put \ mark and press enter
To code group of statements, ;\ will work
list1=[1,2,3]
list2=[4,5,6]
print list1;\
print list2
Will print both the lists
Where as, for Indentation statement, you need :\
for i in list1:\
print i
//double enter
Will show all the elements in the list
x = 3; print x ** 5
should help, but it doesnt matter that its executed the way it is in IDLE.
Just open a new file: File > New window. You can run it by clicking run > run module.
the "\" line at the end of the line works for me. in windows 10 cmd.
Edit: I've also noticed that you have to be consistent with its use, other wise you still get syntax error
Ctrl + Enter enters a new line in Spyder IDE
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
This question already has answers here:
Why doesn't Python have multiline comments?
(18 answers)
Closed 9 years ago.
Is there a mechanism to comment out large blocks of Python code?
Right now, the only ways I can see of commenting out code are to either start every line with a #, or to enclose the code in triple quotes: """.
The problem with these is that inserting # before every line is cumbersome and """ makes the string I want to use as a comment show up in generated documentation.
After reading all comments, the answer seems to be "No".
Python does not have such a mechanism. Prepend a # to each line to block comment. For more information see PEP 8. Most Python IDEs support a mechanism to do the block-commenting-with-hash-signs automatically for you. For example, in IDLE on my machine, it's Alt+3 and Alt+4.
Don't use triple-quotes; as you discovered, this is for documentation strings not block comments, although it has a similar effect. If you're just commenting things out temporarily, this is fine as a temporary measure.
Hide the triple quotes in a context that won't be mistaken for a docstring, eg:
'''
...statements...
''' and None
or:
if False: '''
...statements...
'''
The only cure I know for this is a good editor. Sorry.
The only way you can do this without triple quotes is to add an:
if False:
And then indent all your code. Note that the code will still need to have proper syntax.
Many Python IDEs can add # for you on each selected line, and remove them when un-commenting too. Likewise, if you use vi or Emacs you can create a macro to do this for you for a block of code.
In JetBrains PyCharm on Mac use Command + / to comment/uncomment selected block of code. On Windows, use CTRL + /.
M-x comment-region, in Emacs' Python mode.
At least in VIM you can select the first column of text you want to insert using Block Visual mode (CTRL+V in non-windows VIMs) and then prepend a # before each line using this sequence:
I#<esc>
In Block Visual mode I moves to insert mode with the cursor before the block on its first line. The inserted text is copied before each line in the block.
In vi:
Go to top of block and mark it with letter a.
Go to bottom of block and mark it with letter b
Then do
:'a,'b s!^!#!
comm='''
Junk, or working code
that I need to comment.
'''
You can replace comm by a variable of your choice that is perhaps shorter, easy to touch-type, and you know does not (and will not) occur in your programs. Examples: xxx, oo, null, nil.
In Visual Studio using the Python Tools for Visual Studio, blocks can be commented out by Ctrl+K, Ctrl+C and uncommented by Ctrl+K, Ctrl+U.
I use Notepad++ on a Windows machine, select your code, type CTRL-K. To uncomment you select code and press Ctrl + Shift + K.
Incidentally, Notepad++ works nicely as a Python editor. With auto-completion, code folding, syntax highlighting, and much more. And it's free as in speech and as in beer!
In Eclipse + PyDev, Python block commenting is similar to Eclipse Java block commenting; select the lines you want to comment and use Ctrl + / to comment. To uncomment a commented block, do the same thing.
Yes, there is (depending on your editor). In PyDev (and in Aptana Studio with PyDev):
Ctrl + 4 - comment selected block
Ctrl + 5 - uncomment selected block
The only mechanism to comment out Python code (understood as code ignored by the interpreter) is the #.
As you say, you can also use string literals, that are not ignored by the interpreter, but can be completely irrelevant for the program execution.
In Eclipse using PyDev, you can select a code block and press Ctrl + #.
Triple quotes are OK to me.
You can use ''' foo ''' for docstrings and """ bar """ for comments or vice-versa to make the code more readable.
Another editor-based solution: text "rectangles" in Emacs.
Highlight the code you want to comment out, then C-x-r-t #
To un-comment the code: highlight, then C-x-r-k
I use this all-day, every day. (Assigned to hot-keys, of course.)
This and powerful regex search/replace is the reason I tolerate Emacs's other "eccentricities".
On Eric4 there is an easy way: select a block, type Ctrl+M to comment the whole block or Ctrl+alt+M to uncomment.
Use a nice editor like SciTe, select your code, press Ctrl + Q and done.
If you don't have an editor that supports block comments you can use a triple quoted string at the start and the end of your code block to 'effectively' comment it out. It is not the best practice though.