I am using Python 2.7.3 and I am writing a script which prints the hex byte values of any user-defined file. It is working properly with one problem: each of the values is being printed on a new line. Is it possible to print the values with spaces instead of new lines?
For example, instead of
61
62
I would like to have 61 62
.
Below is my code (..txt
is a file which contains the text 'abcd'
):
#!usr/bin/python
import os
import sys
import time
filename = raw_input("Enter directory of the file you want to convert: ")
f = open(filename, 'rb')
fldt = f.read()
lnfl = len(fldt)
print "Length of file is", lnfl, "bytes. "
orck = 0
while orck < lnfl:
bndt = hex(ord(fldt[orck]))
bndt = bndt[-2:]
orck = orck + 1
ent = chr(13) + chr(10)
entx = str(ent)
bndtx = str(bndt)
bndtx.replace(entx, ' ')
print bndtx
This question is related to
python
python-2.7
printing
newline
First of all print
isn't a function in Python 2, it is a statement.
To suppress the automatic newline add a trailing ,
(comma). Now a space will be used instead of a newline.
Demo:
print 1,
print 2
output:
1 2
Or use Python 3's print()
function:
from __future__ import print_function
print(1, end=' ') # default value of `end` is '\n'
print(2)
As you can clearly see print()
function is much more powerful as we can specify any string to be used as end
rather a fixed space.