whenever I use the write
method from the stdout
or stderr
object in Python's built-in "sys
" module in Python with the Python interpreter, the method also prints an integer representing the number of characters there are in the string after the string that I provided as an argument for the text
parameter for the stdout
or stderr
method, which is really frustating as I only want the text, not also the string length.
For example:
>>> sys.stdout.write('string')
string6
I only wanted to print "'string'
", not the string length (6
) as well.
I have tried to solve this problem by using sys.stdout.write('string')[:-1]
which I think would also remove the number of characters that is placed after the string
I then found out that the number of characters in the string that I provided as an argument is appearing because I was using the interpreter, and the interpreter prints values that are returned by functions but not printed.
So what I want to do is to call sys.stdout.write('test')
but stop it from returning the number of characters in the string that I provided as the text
argument. How would I do this?
sys.stdout.write
also prints the integer after the string that was provided as an argument for the text
parameter in the method call because the write
method of the stdout
object also returns the length of the text
parameter's argument, and the Python REPL/Interpreter also prints out returned values, which is the answer for your problem.
So, to stop it from printing out the length of the text
string, just assign the sys.stdout.write
method call to a variable, as it will call the function and then you can del
the variable after it executes, as you will not want the returned number of characters in the string that was provided for the text
parameter.
Another solution to this problem is by calling the sdtout
object's write
method in a function and then calling that function like:
def show_text(txt):
from sys import stdout
stdout.write(txt)
return
show_text('Hello!)