I have a bit of code from a class which prints a line, and every line is followed by an empty line.
Is there a way to adjust the following code so that I don't have to have those empty lines?
def bfield(self):
self.n=0
for i in self.whole:
for j in i:
print("{:>4}".format(j), end='')
self.n=self.n+1
if self.n==len(i):
print('\n')
self.n=0
I'll agree with Rahul Chowdhury, remove the \n. Pythons print command, by default, will always start a new line after each print call. Hence your addition of '\n' will always result in an empty line.
If you wanted to look into how to get around the whole newline thing python does (every call in its own line), I found this link for you. It is fairly simple to do!
EDIT: It just occurred to me I should maybe list a few of the options just in case the link goes down. Here is one example:
print("Hello ", end = '')
print("World!")
With this, you overwrite the usual python lineend with your end = '' argument.
Another option would be to use the sys library
import sys
and then call the stdout.write() function, like so:
sys.stdout.write("Hello ")
sys.stdout.write("World!")
Related
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. :)
I write many print(...) lines in the code to verify the middle results.
These are handy when you need them, but when everything works well, I need to commit/delete each one of them. Sometimes I found that I may need them again... then I have to go through each print(...) line again.
So is there a switch, that could activate & deactivate those tmp-print lines? While not influencing other print lines that I always want to activate.
Ps: No one wants to do it with if in each line:
if I_want_tmp_print:
print("one of my 100 tmp print lines")
Sometimes if I print enough and I want the debugging 'toggleable' I will write my own function such as:
def prnt(string):
print(string)
return
So then wherever I wan to check my code I will use my function, prnt, instead. And it will display all of the output for me. When I no longer want the output I comment out the print(string) line so nothing is outputted.
If you only want to stop commenting out certain sections of code I will block my code calling a similar function but with a reference number indicating where I have used this in my code.
def prnt(string, idx):
if idx = 1:
print(string)
elif idx = 2:
print(string)
elif idx = 3:
print(string)
...
return
So then say I found out that where I was testing in the idx=1 range and I was calling prnt('string to print', 1) was working as I wanted it to, I can just comment out that print line in my function.
I just want to know why it's doing this, and how to fix it.
I've tried changing the screen size and it still doesn't work.
Any Ideas?
If you try to run the code, choose option C as that's the one that doesn't work for me. It's meant to print off all the moderate/high client's times, but it puts the total time on a new line.
Code + files:
Text file
Python code
Print statements automatically append "\n" to the end of the statement. This ensures that the next print statement will write to a new line instead of on the previous line.
If you want to prevent this, you can use this parameter:
print("This is a: ", end="")
print("message")
Notice the end="" on the first print statement. This will output
This is a: message
If that doesn't solve your issue, I suggest taking a close look at the text you're printing. Make sure that none of the lines have a "\n". Note that reading text from a .txt file will yield lines that automatically have "\n" appended to them.
I am wondering how can I print some strings in a for loop in one line without space between each other.
I know concatenating strings without space in one line, but outside of a for loop:
>>> print('hi'+'hi'+'hi')
hihihi
However, I have no idea how to do that in a for loop.
s = ""
for i in range(3):
s += 'Hi'
print(s)
You can achieve that by skipping print and calling directly stdout:
import sys
for i in range(3):
sys.stdout.write("Hi")
sys.stdout.write("\n")
Output result is HiHiHi. See also this question for a lengthy discussion of the differences between print and stdout.
You can use the print function from Python 3 and specify an end string like this:
# this import is only necessary if you are using Python 2
from __future__ import print_function
for i in range(3):
print('hi', end='')
print()
Alternatively, sys.stdout.write does not add a newline character by default.
I'm trying to write a function to display a custom view when users press the tab button. Apparently "set_completion_display_matches_hook" function is what I need, I can display a custom view, but the problem is that I have to press Enter to get a prompt again.
The solution in Python2 seems to be that (solution here):
def match_display_hook(self, substitution, matches, longest_match_length):
print ''
for match in matches:
print match
print self.prompt.rstrip(),
print readline.get_line_buffer(),
readline.redisplay()
But it doesn't work with Python3. I made these syntax changes :
def match_display_hook(self, substitution, matches, longest_match_length):
print('\n----------------------------------------------\n')
for match in matches:
print(match)
print(self.prompt.rstrip() + readline.get_line_buffer())
readline.redisplay()
Any ideas please ?
First, the Python 2 code uses commas to leave the line unfinished. In Python 3, it's done using end keyword:
print(self.prompt.rstrip(), readline.get_line_buffer(), sep='', end='')
Then, a flush is required to actually display the unfinished line (due to line buffering):
sys.stdout.flush()
The redisplay() call does not seem to be needed.
The final code:
def match_display_hook(self, substitution, matches, longest_match_length):
print()
for match in matches:
print(match)
print(self.prompt.rstrip(), readline.get_line_buffer(), sep='', end='')
sys.stdout.flush()
The redisplay() function
voidrl_redisplay (void)
Change what's displayed on the screen to reflect the current contents of rl_line_buffer.
In your example you have written to stdout, but not changed that buffer.
Print and flush as described by in other answer should work.
One issue you will have, however, is cursor position. Say you have this scenario:
$ cmd some_file
^
+---- User has back-tracked here and want to insert an option.
<TAB> completion with print and flush will put cursor
at end of `some_file' and the line will get an extra 15
spaces after that ...
To remedy this one way is to first get cursor position, then use ANSI sequences to re-position the cursor.
buf = readline.get_line_buffer()
x = readline.get_endidx()
print(self.prompt + buf, end = '')
if x < len(buf):
""" Set cursor at old column position """
print("\r\033[%dC" % (x + len(self.prompt)), end = '')
sys.stdout.flush()
Now, of course, you get another issue if prompt has ANSI sequences in-iteself. Typically color or the like. Then you can not use len(prompt) but have to find printed / visible length.
One has to use open and close bytes elsewhere, typically \0x01 and \0x02 respectively.
So one typically get:
prompt = '\001\033[31;1m\002VISIBLE_TEXT\001\033[0m\002 '
instead of:
prompt = '\033[31;1mVISIBLE_TEXT\033[0m '
With those guards it should be easy enough to strip out the visible text.
Typically something like:
clean_prompt = re.sub(r'\001[^\002]*\002', '', prompt))
Cache the length of that and use when printing the readline manually. Note that you also have to remove the guards when using it manually - as in the hook function. (But it is needed in input(prompt)
this one worked for me for redisplaying substitution and the end of matches display for python3:
def match_display_hook(self, substitution, matches, longest_match_length):
print("")
for match in matches:
print(match)
print("")
sys.stdout.write(substitution)
sys.stdout.flush()
return None
while previous ones using print prompt didn't. (didn't get to the bottom of the problem)