如何在 Python 2.7 中打印由空格而不是换行符分隔的值 [英] How to print values separated by spaces instead of new lines in Python 2.7

查看:52
本文介绍了如何在 Python 2.7 中打印由空格而不是换行符分隔的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Python 2.7.3 并且我正在编写一个脚本来打印任何用户定义文件的十六进制字节值.它工作正常,但存在一个问题:每个值都打印在新行上.是否可以用空格而不是换行来打印值?

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?

例如,代替

61

62

我想要61 62.

下面是我的代码(..txt 是一个包含文本 'abcd' 的文件):

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

推荐答案

首先 print 在 Python 2 中不是一个函数,它是一个语句.

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.

演示:

print 1,
print 2

输出:

1 2

或者使用 Python 3 的 print() 函数:

Or use Python 3's print() function:

from __future__ import print_function
print(1, end=' ') # default value of `end` is '\n'
print(2)

你可以清楚地看到 print() 函数更强大,因为我们可以指定任何字符串用作 end 而不是一个固定的空间.

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.

这篇关于如何在 Python 2.7 中打印由空格而不是换行符分隔的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆