getting rid of trailing output - python

How do i get rid of the extra character at the end of a line when i flush output?
Output:
{Fifth Level} Last Key Ran: 7 Output: -7 =
That '=' is what i want to get rid of.
code:
for number in str(fourth_level):
x=int(number)
x=x^(priv_key-pub_key)
print "\r{Fifth Level} Last Key Ran:",str(number),"Output:",x,
sys.stdout.flush()
time.sleep(sleep_time)
fifth_level.append(x)
Also is there any way to get multiple lines outputting data at the same time without going down one line or changing format? Using flush it gets rid of the second line output.

As a side note, check the ,x, part of the print statement. That 'x' is fishy.
For string manipulations, try writing everything into a temporary string first. You can then edit that string. This will give you more control over editing it.
Also, rstrip might do the trick if the characters being displayed are consistent.
Reference:
* http://docs.python.org/library/string.html
"string.rstrip(s[, chars]) Return a copy of the string with trailing characters removed."

Related

Delete last character in stdout buffer

In Python 3.7, I am trying to write a JSON array to stdout and I would like to remove the final comma in the array
sys.stdout.write("[")
[sys.stdout.write(json.dumps(x, separators=(',', ': ')) + ",") for x in list]
sys.stdout.write("\b]") # I want to remove the final ',' from above.
I know sys.stdout is buffered, so what I'd like to do is remove the last character in that buffer before the flush. The only problem is I don't know how to properly access that buffer as well as ensure the final byte is not written.
I messed with the \b character however that does nothing, all that happens is the \b character becomes part of the output.
As a background, the stdout is going into an Apache NiFi flow (not to a console window). I'd much rather use stdout and not a secondary in-memory buffer as that feels like such a waste of memory. It'd be great if I could remove the last byte of the stdout buffer before flushing.
EDIT:
Some folks in the comments are suggesting my use of list comprehensions isn't the way to go here and instead run json.dumps on the list. If anyone has an example of how to use this and ensure the last element doesn't have a trailing comma, please show it!
The simplest solution is just to dump the whole list at once:
sys.stdout.write(json.dumps(list, separators=(',', ': '))
But if you really need to write each element separately you could make the comma conditional:
last_index = len(list) - 1
sys.stdout.write("[")
for i, x in enumerate(list):
sys.stdout.write(json.dumps(x, separators=(',', ': '))
if i < last_index:
sys.stdout.write(',')
sys.stdout.write("]")

Python - \n appearing in concatenated strings

I've been having an issue with my Python code. I am trying to concatenate the value of two string objects, but when I run the code it keeps printing a '\n' between the two strings.
My code:
while i < len(valList):
curVal = valList[i]
print(curVal)
markupConstant = 'markup.txt'
markupFileName = curVal + markupConstant
markupFile = open(markupFileName)
Now when I run this, it gives me this error:
OSError: [Errno 22] Invalid argument: 'cornWhiteTrimmed\nmarkup.txt'
See that \n between the two strings? I've dissected the code a bit by printing each string individually, and neither one contains a \n on its own. Any ideas as to what I'm doing wrong?
Thanks in advance!
The concatenation itself doesn't add the \n for sure. valList is probably the result of calling readlines() on a file object, so each element in it will have a trailing \n. Call strip on each element before using it:
while i < len(valList):
curVal = valList[i].strip()
print(curVal)
markupConstant = 'markup.txt'
markupFileName = curVal + markupConstant
markupFile = open(markupFileName)
The reason you are not seeing the \n when you actually print out the python statements is because \n is technically the newline character. You will not see this when you actually print, it will only skip to a new line. The problem is when you have this in the middle of your two strings, it is going to cause problems. The solution to your issue is the strip method. You can read into its documentation here (https://www.tutorialspoint.com/python/string_strip.htm) but basically you can use this method to strip the newline character off of any of your strings.
Just to make an addition to the other answers explaining why this came about:
When you need to actually inspect what characters a string contains, you can't simply print it. Many characters are "invisible" when printed.
Turn the string into a list first:
list(curVal)
Or my personal favorite:
[c for c in curVal]
These will create lists that properly show all hard to see characters.

Python 3 print to file creating errant new lines

I wrote code to read in url and IP data with IP as the key for urls visited. I am attempting to print the IP key then the number of url visits for each.
The problem is that when printing to my file there is a new line after some IPs.
Here is the output section of code:
`for key, value in ipVisit.items():
outputF.write(key + " " + str(len(ipVisit[key]))+ '\n' )`
Even if I increase or decrease the number of spaces between key and # of visits the third output is always the only one to be on one line. Here is the output:
194.33.212.111
28
12.65.4.100
28
205.23.104.49 31
205.23.104.49
29
Did I do something stupid with my loop? How can I fix this?
One thing I've found to be very helpful when writing to files is to ignore the write method entirely:
for key, value in ipVisit.items():
print(key + " " + str(len(ipVisit[key])), file=outputF)
This has the possibly-great side effect of outputting to stdout if outputF==None, which I've taken advantage of for command line programs in the past (passing in the output file vs. - or something).
Using print, you'll get the newline semantics that you're familiar with and the commenter's suggestion of .rstrip() will take care of any leftover errant newline characters.
EDIT: It might also be wise to avoid string building with the + operator and instead use the format method. Also, you have the value already form your for loop, there's no need to index into ipVisit again:
for key, value in ipVisit.items():
print('{} {}'.format(key, len(value)), file=outputF)
# or rstrip if there's still extra newlines
print('{} {}'.format(key.rstrip(), len(value)), file=outputF) # this will only work if you're sure `key` is a str

Why `print '1\x08'` results 1 meanwhile `print '1\x082'` results 2?

Today, I'm learning the built-in function chr. And through ascii-table search, I found \x08 means backspace. So I played a bit with it. But the result confused me:
In [52]: print '1\x08'
1
In [53]: print '1\x082'
2
It seems that only follow by another character, \x08 will behave like a backspace, why does this happened? How \x08 behaves in a string?
It's behaving like a backspace in both cases, which is to say it moves your cursor back one space. It does not, however, delete what's there unless you write something else. So in the first case, the 1 remains, but in the second it is overwritten with a 2.
Backspace only moves the cursor by one character, it does not actually delete it. This for example results in 193:
print('123\x08\x089')
You can use space to actually "delete" the character...
1---- backspace simply move the cursor to the left one space, and
if you use the work or other editor it will also delete the left one character.
and what you must know is that backspace is also a character the same as 1 or a.
2---- the terminal as our default output device, you can also put him as a file.
So if you use
print '1\x08'
it means that you write a 1 and a backspace in the file stdout.
if you read the file, the system reads 1 + breakspace, you will get an 1.
and if you use
print '1\x082'
it means that you write a 1, a backspace and a 2 in the file stdout.
if you read the file, the system get 1 + breakspace + 2, when you print them, you will only get an 2, because it covers the first 1 when you use backspace.
for detail you can see the next test code
if __name__ == "__main__":
print "1\x08"
print "1\x082"
f = open("1.txt", "w")
f.write("1\x08\x082")
f.close();
f = open("1.txt", "r")
str = f.readlines( )
print len(str), str
for s in str:
print "s=|" + s + "|"
you can see the string s=|1\x08\x082| display s=2|. becasue the |1 not display when backspace two times.

python lstrip(' ') removes lines

first of all, I'm new to python, so maybe my code is a little weird or bordering to be wrong, but it works, so there is that.
I've been googleing for this problem, but can't find anyone who writes about, I got this huge list written like this
1 2 3 4 5
2 2 2 2 2
3 3 3 3 3
etc, note that it is spaces and not tab, and this I can't change, since I'm working with a print out from ls-dyna
So I am using this script to remove the whitespaces before the numbers, since they have been giving me troubles when trying to format the numbers into a matrix and then i remove the empty lines afterwards
for line in input:
print >> output, line.lstrip(' ')
but for some reason, I have 4442 lines (and here I mean writen lines, which is easy to track since they are enumerated) but the output only has 4411, so it removes 31 lines, with numbers I need
Why is this?
The lstrip() won't remove lines because it is used inside the print statement which will always append a newline character (the way you use it). But the for line in input might step through the list of lines in an unexpected way, i. e. it could skip lines or combine them in a manner you didn't expect.
Maybe newline and carriage return characters result in this strange problem.
I propose to let the .lstrip(' ') away for testing and compare the output with the input to find the places where something gets changed. Probably you should use output.write(line) to circumvent all the automatics of the print statement (especially appending newline characters).
Then you should use a special separator when outputting (output.write('###' + line) or similar) to find out how the iteration through the input takes place.

Categories

Resources