python print() 函数中的新行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18179606/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 10:06:38  来源:igfitidea点击:

New line in python print() function

pythonpython-2.7printingnewline

提问by Anonymous Noone

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 are being printed on a new line. Is it possible to print the values with spaces instead of new lines?

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

For example, instead of

例如,代替

61

62

I would like to have 61 62.

我想有61 62

Below is my code (..txtis a file which contains the text 'abcd'):

下面是我的代码(..txt是一个包含文本的文件'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

回答by Ashwini Chaudhary

First of all printisn't a function in Python 2, it is a statement.

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

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:

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

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 endrather a fixed space.

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

回答by 7stud

This does almost everything you want:

这几乎可以满足您的所有需求:

f = open('data.txt', 'rb')

while True:
    char = f.read(1)
    if not char: break
    print "{:02x}".format(ord(char)),

With data.txt created like this:

使用 data.txt 创建如下:

f = open('data.txt', 'wb')
f.write("ab\r\ncd")
f.close()

I get the following output:

我得到以下输出:

61 62 0d 0a 63 64

tl;dr-- 1. You are using poor variable names. 2. You are slicing your hex strings incorrectly. 3. Your code is never going to replace any newlines. You may just want to forget about that feature. You do not quite yet understand the difference between a character, its integer code, and the hex string that represents the integer. They are all different: two are strings and one is an integer, and none of them are equal to each other. 4. For some files, you shouldn't remove newlines.

tl;dr-- 1. 你使用的变量名很糟糕。2. 您对十六进制字符串的切片不正确。3. 你的代码永远不会替换任何换行符。您可能只想忘记该功能。您还不太了解字符、其整数代码和表示整数的十六进制字符串之间的区别。它们都是不同的:两个是字符串,一个是整数,它们都不相等。4. 对于某些文件,您不应该删除换行符。

===

===

1. Your variable names are horrendous.

1. 你的变量名太可怕了。

That's fine if you never want to ask anybody questions. But since every one needs to ask questions, you need to use descriptive variable names that anyone can understand. Your variable names are only slightly better than these:

如果你从不想问任何人问题,那很好。但是由于每个人都需要提出问题,因此您需要使用任何人都可以理解的描述性变量名称。你的变量名只比这些好一点:

fname = 'data.txt'
f = open(fname, 'rb')
xxxyxx = f.read()

xxyxxx = len(xxxyxx)
print "Length of file is", xxyxxx, "bytes. "
yxxxxx = 0

while yxxxxx < xxyxxx:
    xyxxxx = hex(ord(xxxyxx[yxxxxx]))
    xyxxxx = xyxxxx[-2:]
    yxxxxx = yxxxxx + 1
    xxxxxy = chr(13) + chr(10)
    xxxxyx = str(xxxxxy)
    xyxxxxx = str(xyxxxx)
    xyxxxxx.replace(xxxxyx, ' ')
    print xyxxxxx

That program runs fine, but it is impossible to understand.

该程序运行良好,但无法理解。

2. The hex() function produces strings of different lengths.

2. hex() 函数产生不同长度的字符串。

For instance,

例如,

print hex(61)
print hex(15)

--output:--
0x3d
0xf

And taking the slice [-2:] for each of those strings gives you:

并为每个字符串取切片 [-2:] 给你:

3d
xf

See how you got the 'x' in the second one? The slice:

看看你是如何在第二个中得到“x”的?切片:

[-2:] 

says to go to the end of the string and back up two characters, then grab the rest of the string. Instead of doing that, take the slice starting 3 characters in from the beginning:

说到字符串的末尾并备份两个字符,然后获取字符串的其余部分。不要这样做,而是从头开始取 3 个字符的切片:

[2:]  

3. Your code will never replace any newlines.

3. 你的代码永远不会替换任何换行符。

Suppose your file has these two consecutive characters:

假设你的文件有这两个连续的字符:

"\r\n"

Now you read in the first character, "\r", and convert it to an integer, ord("\r"), giving you the integer 13. Now you convert that to a string, hex(13), which gives you the string "0xd", and you slice off the first two characters giving you:

现在您读入第一个字符“\r”,并将其转换为整数 ord("\r"),得到整数 13。现在将其转换为字符串 hex(13),得到string "0xd",然后你切掉前两个字符给你:

"d"

Next, this line in your code:

接下来,代码中的这一行:

bndtx.replace(entx, ' ')

tries to find every occurrence of the string "\r\n"in the string "d"and replace it. There is never going to be any replacement because the replacement string is two characters long and the string "d"is one character long.

尝试查找字符串"\r\n"中出现的每个字符串"d"并替换它。永远不会有任何替换,因为替换字符串是两个字符长而字符串"d"是一个字符长。

The replacement won't work for "\r\n"and "0d"either. But at least now there is a possibility it could work because both strings have two characters. Let's reduce both strings to a common denominator: ascii codes. The ascii code for "\r" is 13, and the ascii code for "\n" is 10. Now what about the string "0d"? The ascii code for the character"0"is 48, and the ascii code for the character "d" is 100. Those strings do not have a single character in common. Even this doesn't work:

更换不会为工作"\r\n""0d"无论是。但至少现在有可能它可以工作,因为两个字符串都有两个字符。让我们将两个字符串简化为一个公分母:ascii 代码。"\r" 的 ascii 代码是 13,而 "\n" 的 ascii 代码是 10。那么字符串"0d"呢?字符的ascii 码"0"是48,字符“d”的ascii 码是100。这些字符串没有一个共同的字符。即使这不起作用:

 x = '0d' + '0a'
 x.replace("\r\n", " ")
 print x

 --output:--
 '0d0a'

Nor will this:

这也不会:

x = 'd' + 'a'
x.replace("\r\n", " ")
print x

--output:--
da

The bottom line is: converting a character to an integer then to a hex string does not end up giving you the original character--they are just different strings. So if you do this:

底线是:将字符转换为整数然后转换为十六进制字符串最终不会为您提供原始字符——它们只是不同的字符串。所以如果你这样做:

char = "a"
code = ord(char)
hex_str = hex(code)

print char.replace(hex_str, " ")

...you can't expect "a" to be replaced by a space. If you examine the output here:

...你不能指望“a”被一个空格代替。如果您检查此处的输出:

char = "a"
print repr(char)

code = ord(char)
print repr(code)

hex_str = hex(code)
print repr(hex_str)

print repr(
    char.replace(hex_str, " ")
)

--output:--
'a'
97
'0x61'
'a'

You can see that 'a' is a string with one character in it, and '0x61'is a string with 4 characters in it: '0', 'x', '6', and '1', and you can never find a four character string inside a one character string.

可以看到 'a' 是一个包含一个字符的字符串,并且'0x61'是一个包含 4 个字符的字符串:'0''x''6'、 和'1',并且在一个字符的字符串中永远找不到四字符的字符串。

4) Removing newlines can corrupt the data.

4) 删除换行符可能会损坏数据。

For some files, you do not want to replace newlines. For instance, if you were reading in a .jpg file, which is a file that contains a bunch of integers representing colors in an image, and some colors in the image happened to be represented by the number 13 followed by the number 10, your code would eliminate those colors from the output.

对于某些文件,您不想替换换行符。例如,如果您正在阅读一个 .jpg 文件,该文件包含一组表示图像颜色的整数,而图像中的某些颜色恰好由数字 13 和数字 10 表示,您的代码将从输出中消除这些颜色。

However, if you are writing a program to read only textfiles, then replacing newlines is fine. But then, different operating systems use different newlines. You are trying to replace Windows newlines(\r\n), which means your program won't work on files created by a Mac or Linux computer, which use \n for newlines. There are easy ways to solve that, but maybe you don't want to worry about that just yet.

但是,如果您正在编写一个只读取文本文件的程序,那么替换换行符就可以了。但是,不同的操作系统使用不同的换行符。您正在尝试替换 Windows 换行符 (\r\n),这意味着您的程序无法处理由 Mac 或 Linux 计算机创建的文件,这些文件使用 \n 作为换行符。有一些简单的方法可以解决这个问题,但也许您还不想担心这个问题。

I hope all that's not too confusing.

我希望所有这些都不会太令人困惑。