Python 没有换行符打印(print 'a',)打印一个空格,如何删除?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4499073/
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-18 16:01:29  来源:igfitidea点击:

Printing without newline (print 'a',) prints a space, how to remove?

pythonstringprintingpython-2.x

提问by pythonFoo

I have this code:

我有这个代码:

>>> for i in xrange(20):
...     print 'a',
... 
a a a a a a a a a a a a a a a a a a a a

I want to output 'a', without ' 'like this:

我想输出'a',而不是' '这样:

aaaaaaaaaaaaaaaaaaaa

Is it possible?

是否可以?

采纳答案by moinudin

There are a number of ways of achieving your result. If you're just wanting a solution for your case, use string multiplicationas @Antmentions. This is only going to work if each of your printstatements prints the same string. Note that it works for multiplication of any length string (e.g. 'foo' * 20works).

有多种方法可以实现您的结果。如果您只是想要一个解决方案,请使用字符串乘法作为@Ant提及。只有当您的每个print语句都打印相同的字符串时,这才会起作用。请注意,它适用于任何长度字符串的乘法(例如'foo' * 20作品)。

>>> print 'a' * 20
aaaaaaaaaaaaaaaaaaaa

If you want to do this in general, build up a string and then print it once. This will consume a bit of memory for the string, but only make a single call to print. Note that string concatenation using +=is now linear in the size of the string you're concatenating so this will be fast.

如果您想在一般情况下执行此操作,请构建一个字符串,然后打印一次。这将为字符串消耗一些内存,但只对print. 请注意,使用的字符串连接+=现在与您要连接的字符串的大小呈线性关系,因此速度会很快。

>>> for i in xrange(20):
...     s += 'a'
... 
>>> print s
aaaaaaaaaaaaaaaaaaaa

Or you can do it more directly using sys.stdout.write(), which printis a wrapper around. This will write only the raw string you give it, without any formatting. Note that no newline is printed even at the end of the 20 as.

或者您可以更直接地使用sys.stdout 来完成write(),它print是一个包装器。这将只写入您提供的原始字符串,没有任何格式。请注意,即使在 20a秒结束时也不会打印换行符。

>>> import sys
>>> for i in xrange(20):
...     sys.stdout.write('a')
... 
aaaaaaaaaaaaaaaaaaaa>>> 

Python 3 changes the printstatement into a print() function, which allows you to set an endparameter. You can use it in >=2.6 by importing from __future__. I'd avoid this in any serious 2.x code though, as it will be a little confusing for those who have never used 3.x. However, it should give you a taste of some of the goodness 3.x brings.

Python 3 将print语句更改为print() 函数,它允许您设置end参数。您可以通过导入 from 来在 >=2.6 中使用它__future__。不过,我会在任何严肃的 2.x 代码中避免这种情况,因为对于那些从未使用过 3.x 的人来说,这会有点混乱。但是,它应该让您体验 3.x 带来的一些好处。

>>> from __future__ import print_function
>>> for i in xrange(20):
...     print('a', end='')
... 
aaaaaaaaaaaaaaaaaaaa>>> 

回答by Ant

without what? do you mean

没有什么?你的意思是

>>> print 'a' * 20
aaaaaaaaaaaaaaaaaaaa

?

?

回答by jensgram

Either what Antsays, or accumulate into a string, then print once:

要么Ant说的,要么累积成一个字符串,然后打印一次:

s = '';
for i in xrange(20):
    s += 'a'
print s

回答by P?r Wieslander

You can suppress the space by printing an empty string to stdout between the printstatements.

您可以通过在print语句之间将空字符串打印到 stdout 来抑制空格。

>>> import sys
>>> for i in range(20):
...   print 'a',
...   sys.stdout.write('')
... 
aaaaaaaaaaaaaaaaaaaa

However, a cleaner solution is to first build the entire string you'd like to print and then output it with a single printstatement.

但是,更简洁的解决方案是首先构建您想要打印的整个字符串,然后使用单个print语句输出它。

回答by Lucas Moeskops

You could print a backspace character ('\b'):

您可以打印退格字符 ( '\b'):

for i in xrange(20):
    print '\ba',

result:

结果:

aaaaaaaaaaaaaaaaaaaa

回答by Antoine Pelisse

From PEP 3105: print As a Functionin the What's New in Python 2.6document:

PEP 3105:打印作为一个函数什么新的Python 2.6的文档:

>>> from __future__ import print_function
>>> print('a', end='')

Obviously that only works with python 3.0 or higher (or 2.6+ with a from __future__ import print_functionat the beginning). The printstatement was removed and became the print()function by default in Python 3.0.

显然,这仅适用于 python 3.0 或更高版本(或开头带有 a 的 2.6+ from __future__ import print_function)。该print语句print()在 Python 3.0 中被删除并默认成为函数。

回答by codeape

Python 3.x:

Python 3.x:

for i in range(20):
    print('a', end='')

Python 2.6 or 2.7:

Python 2.6 或 2.7:

from __future__ import print_function
for i in xrange(20):
    print('a', end='')

回答by daviewales

If you want them to show up one at a time, you can do this:

如果您希望它们一次显示一个,您可以这样做:

import time
import sys
for i in range(20):
    sys.stdout.write('a')
    sys.stdout.flush()
    time.sleep(0.5)

sys.stdout.flush()is necessary to force the character to be written each time the loop is run.

sys.stdout.flush()必须在每次运行循环时强制写入字符。

回答by Kyle Siopiolosz

Just as a side note:

正如旁注:

Printing is O(1) but building a string and then printing is O(n), where n is the total number of characters in the string. So yes, while building the string is "cleaner", it's not the most efficient method of doing so.

打印是 O(1) 但构建一个字符串然后打印是 O(n),其中 n 是字符串中的字符总数。所以是的,虽然构建字符串“更干净”,但它并不是最有效的方法。

The way I would do it is as follows:

我会这样做的方式如下:

from sys import stdout
printf = stdout.write

Now you have a "print function" that prints out any string you give it without returning the new line character each time.

现在你有了一个“打印函数”,它打印出你给它的任何字符串,而不用每次都返回换行符。

printf("Hello,")
printf("World!")

The output will be: Hello, World!

输出将是:你好,世界!

However, if you want to print integers, floats, or other non-string values, you'll have to convert them to a string with the str() function.

但是,如果要打印整数、浮点数或其他非字符串值,则必须使用 str() 函数将它们转换为字符串。

printf(str(2) + " " + str(4))

The output will be: 2 4

输出将是:2 4

回答by SHAH MD IMRAN HOSSAIN

WOW!!!

哇!!!

It's pretty long timeago

这是很久以前

Now, In python 3.xit will be pretty easy

现在,在python 3.x 中,这将非常容易

code:

代码:

for i in range(20):
      print('a',end='') # here end variable will clarify what you want in 
                        # end of the code

output:

输出:

aaaaaaaaaaaaaaaaaaaa 

More about print() function

更多关于 print() 函数

print(value1,value2,value3,sep='-',end='\n',file=sys.stdout,flush=False)

Here:

在这里

value1,value2,value3

you can print multiple valuesusing commas

您可以使用逗号打印多个值

sep = '-'

3 values will be separated by '-' character

3 个值将由“-”字符分隔

you can use any character instead of that even string like sep='@' or sep='good'

您可以使用任何字符而不是像 sep='@' 或 sep='good' 这样的偶数字符串

end='\n'

by default print function put '\n' charater at the end of output

默认情况下,打印函数将 '\n' 字符放在输出的末尾

but you can use any character or string by changing end variale value

但是您可以通过更改结束变量值来使用任何字符或字符串

like end='$' or end='.' or end='Hello'

像 end='$' 或 end='.' 或 end='你好'

file=sys.stdout

this is a default value, system standard output

这是默认值,系统标准输出

using this argument you can create a output file streamlike

使用此参数,您可以创建一个输出文件流,

print("I am a Programmer", file=open("output.txt", "w"))

by this code you will create a file named output.txtwhere your output I am a Programmerwill be stored

通过此代码,您将创建一个名为output.txt的文件,其中将存储您的输出 I am a Programmer

flush = False

It's a default value using flush=Trueyou can forcibly flush the stream

这是使用flush = True的默认值,您可以强制刷新流