Typing effect Python [duplicate] - python

I am writing a program in Python and want to replace the last character printed in the terminal with another character.
Pseudo code is:
print "Ofen",
print "\b", # NOT NECCESARILY \b, BUT the wanted print statement that will erase the last character printed
print "r"
I'm using Windows8 OS, Python 2.7, and the regular interpreter.
All of the options I saw so far didn't work for me. (such as: \010, '\033[#D' (# is 1), '\r').
These options were suggested in other Stack Overflow questions or other resources and don't seem to work for me.
EDIT: also using sys.stdout.write doesn't change the affect. It just doesn't erase the last printed character. Instead, when using sys.stdout.write, my output is:
Ofenr # with a square before 'r'
My questions:
Why don't these options work?
How do I achieve the desired output?
Is this related to Windows OS or Python 2.7?
When I find how to do it, is it possible to erase manually (using the wanted eraser), delete the '\n' that is printed in python's print statement?

When using print in python a line feed (aka '\n') is added. You should use sys.stdout.write() instead.
import sys
sys.stdout.write("Ofen")
sys.stdout.write("\b")
sys.stdout.write("r")
sys.stdout.flush()
Output: Ofer

You can also import the print function from Python 3. The optional end argument can be any string that will be added. In your case it is just an empty string.
from __future__ import print_function # Only needed in Python 2.X
print("Ofen",end="")
print("\b",end="") # NOT NECCESARILY \b, BUT the wanted print statement that will erase the last character printed
print("r")
Output
Ofer

I think string stripping would help you. Save the input and just print the string upto the length of string -1 .
Instance
x = "Ofen"
print (x[:-1] + "r")
would give you the result
Ofer
Hope this helps. :)

Related

How can I insert a certain character before and after another certain character?

I am writing a short Python 3 program that takes a Python 2 script, and fixes the way Python 2's printing function worked, and fixes it to make it work with Python 3. This is useful for some scripts that use Python 2, but the only issue is that there's tons of incorrect examples of printing according to Python 3.
Example:
Let's say I have a Python 2 script that looks like this:
print 'hello world'
I would want to use my program to convert it to this:
print('hello world')
So far, I have this, which strips the new lines, replaces the first instance of the quotation mark with an opening parenthesis, and replaces the second instance of the quotation mark with a closing parenthesis.
if "print" in ReadNextLine:
RawInput = ReadNextLine.replace(" ", "")
ReadyForFixing = RawInput.strip("\n")
replaceportion1 = ReadyForFixing.replace("'", "(", 1)
replaceportion2 = replaceportion1.replace("'", ")")
print(replaceportion2)
Output:
print(Line1)
print(Line2)
print(Line3)
print(Line4)
print(Line5)
I was wondering if there was some way to insert a quotation mark after the first parenthesis, and before the second parenthesis.
Keep in mind that these outputs will be dynamic according to whatever the file that the user needs fixed inputs.
I plan on posting this project on Github. Let me know if you would like any crediting, since you may have technically collaborated.

Python 2.7 VSCODE doesn't get the correct length of input string

in my class we are studying python 2.7. I am using vscode to test the exercises.
exercise 1: read user input and print the length. If the user write
exit the program finish.
My code is follow:
myexit=False
while (myexit!=True):
#read user input
txt=raw_input("write a string or write exit to go out: ")
#print the user input string
print txt
if (str(txt)=='exit'):
myexit=True#exit from while
else:
print len(txt) #print the string length
print "finish"
when i test the code i get always the length of the string +1
example: if i write foo the output is 4 and no 3. When i write exit i
don't go out from the while and the output is 5.
Where i wrong ?
I have missed a module?
Thanks for your help
I am not sure exactly why this is happening, and I don't have access to a windows machine to test/verify but based on the comments above, it appears that on the version of python you are using that raw_input is only stripping the newline(\n) and not the carriage return(\r). Windows uses \r\n while unix uses \n. When raw input returns the \r is still on the string, hence the extra char. A useful debugging technique at the cli is to use the function repr() on the value to see exactly how it is represented. This is helpful to locate any stray control or invisible chars in strings.
The function rstrip() will remove all whitespace from the right side of the string, which in this case should safely remove the stray \r. It should also be safe if this code is running on a *nix like system as rstrip() will only remove the whitespace if it is present. You can also specify a set of char to strip, so if you would would like to be pedantic, you could use rstrip("\r").
txt=raw_input("write a string or write exit to go out: ").rstrip("\r")
Should fix the issue while still maintaining compatibility on different versions.

Unprint a line on the console in Python?

Is it possible to manipulate lines of text that have already been printed to the console?
For example,
import time
for k in range(1,100):
print(str(k)+"/"+"100")
time.sleep(0.03)
#>> Clear the most recent line printed to the console
print("ready or not here I come!")
I've seen some things for using custom DOS consoles under Windows, but I would really like something that works on the command_line like does print without any additional canvases.
Does this exist? If it doesn’t, why not?
P.S.: I was trying to use curses, and it was causing problems with my command line behaviour outside of Python. (After erroring out of a Python script with curses in it, my Bash shell stopped printing newline -unacceptable- ).
What you're looking for is:
print("{}/100".format(k), "\r", end="")
\r is carriage return, which returns the cursor to the beginning of the line. In effect, whatever is printed will overwrite the previous printed text. end="" is to prevent \n after printing (to stay on the same line).
A simpler form as suggested by sonrad10 in the comments:
print("{}/100".format(k), end="\r")
Here, we're simply replacing the end character with \r instead of \n.
In Python 2, the same can be achieved with:
print "{}/100".format(k), "\r",
What you need are ANSI Command Codes.
http://en.wikipedia.org/wiki/ANSI_escape_code#CSI_codes
You also need code to activate ANSI Command Codes. I would use Colorama.
https://pypi.python.org/pypi/colorama
OR
Use curses (Python 3.4+) module.
The simplest method (at least for Python 2.7) is to use the syntax:
print 'message', '\r',
print 'this new message now covers the previous'
Notice the extra ',' at the end of the first print. This makes print stay on the same line. Meanwhile, the '\r' puts the print at the beginning of that line. So the second print statement overwrites the first.

How can I use \r to make Python print on the same line?

Can someone please thoroughly explain how a '\r' works in Python?
Why isn't the following code printing out anything on the screen?
#!/usr/bin/python
from time import sleep
for x in range(10000):
print "%d\r" % x,
sleep(1)
Your output is being buffered, so it doesn't show up immediately. By the time it does, it's being clobbered by the shell or interpreter prompt.
Solve this by flushing each time you print:
#!/usr/bin/python
from time import sleep
import sys
for x in range(10000):
print "%d\r" % x,
sys.stdout.flush()
sleep(1)
'\r' is just a another ASCII code character. By definition it is a CR or carriage return. It's the terminal or console being used that will determine how to interpret it. Windows and DOS systems usually expect every line to end in CR/LF ('\r\n') while Linux systems are usually just LF ('\n'), classic Mac was just CR ('\r'); but even on these individual systems you can usually tell your terminal emulator how to interpret CR and LF characters.
Historically (as a typewriter worked), LF bumped the cursor to the next line and CR brought it back to the first column.
To answer the question about why nothing is printing: remove the comma at the end of your print line.
Do this instead:
print "\r%d" % x,
This has nothing to do with \r. The problem is the trailing , in your print statement. It's trying to print the last value on the line, and the , is creating a tuple where the last value is empty. Lose the , and it'll work as intended.
Edit:
I'm not sure it's actually correct to say that it's creating a tuple, but either way that's the source of your problem.

print to print as comma separated values on the same line

I am unable to print the output on a single line without printing new lines, the following code shows syntax error:
print( "tiers found:"+eval("str.lower(tier.attrib['TIER_ID'])"), end=', ')
^
SyntaxError: invalid syntax
But this works fine:
print( "tiers found:"+eval("str.lower(tier.attrib['TIER_ID'])"))
the print statement is in a for loop and I require to print the output as comma separated list.
So whats the problem here?
Why are you using eval on a completely sane statement?
from __future__ import print_function
print('tiers found: {0}'.format(tier.attrib['TIER_ID'].lower()), end=',')
One cause could be that the first piece of code is executed with Python 2 and the second one with Python 3.
If that's not it, then try end=", ". My guess is that the second single quote isn't actually the quote that you want (i.e. it's backtick instead of single quote or something like that).
Or maybe there is an illegal character in there that you can't see in your editor.

Categories