How to Delete Comma At the End of the Output in Python

How to remove comma at the end of integer printing?

I would try adding the results to a string or array and then trimming the last character before printing the results. Something like this:

import zlib
def crc32(filename="input.hex", chunksize=65536):
with open(filename, "rb") as f1:
while (chunk := f1.read(chunksize)) :
file = open('output_file.crc', "w")
crc = zlib.crc32(chunk) & 0xFFFF_FFFF
result = ''
for i in range(4):
byte = (crc >> (8*i)) & 0xFF
file.write(f'0x{byte:02X}, ')
result += f'0x{byte:02X},\n'
print(result[:-2])
crc32()

Output

0xE0,
0x24,
0x7A,
0x73

Edit: See @quamrana answer for a more elegant solution.

How to remove the last comma from each line in a string?

This is not too good in terms of performance if your string is very long, but it should do

"\n".join(x[:-1] for x in output.splitlines())

How can I delete comma at the end of the output in Python?

Python strings have a join() function:

ls = ['a','b','c']
print(",".join(ls)) # prints "a,b,c"

Python also has what is called a 'list comprehension', that you can use like so:

alphabet='AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz'
word=str(input())
matches = [l for l in word if l in alphabet]
print(",".join(sorted(matches)))

All the list comprehension does is put l in the list if it is in alphabet. All the candidate ls are taken from the word variable.

sorted is a function that will do a simple sort (though more complex sorts are possible).

Finally; here are a few other fun options that all result in "a,b,c,d":

"a,b,c,d,"[:-1] . # list-slice
"a,b,c,d,".strip(",") . # String strip

How to remove Comma printing at the last of the integer List?

If you change the variable of n in the function, you can reference your global n and check against that, and not print the last comma.

n = int(input())
k = int(input())

def printPattern(x):

# Base case (When n becomes 0 or negative)
if (x == 0 or x < 0):
print(x, end = ", ")
return
print(x, end = ", ")
printPattern(x - k)
if (x == n):
print(x)
else:
print(x, end = ", ")
printPattern(n)


Related Topics



Leave a reply



Submit