问题:如何在没有换行符或空格的情况下进行打印?

我想在里面做 。我想在这个例子中做什么

在C中:

#include <stdio.h>

int main() {
    int i;
    for (i=0; i<10; i++) printf(".");
    return 0;
}

输出:

..........

在Python中:

>>> for i in range(10): print('.')
.
.
.
.
.
.
.
.
.
.
>>> print('.', '.', '.', '.', '.', '.', '.', '.', '.', '.')
. . . . . . . . . .

在Python中print会添加\n或空格,如何避免呢?现在,这只是一个例子,不要告诉我我可以先构建一个字符串然后再打印它。我想知道如何将字符串“附加”到stdout

I’d like to do it in . What I’d like to do in this example in :

In C:

#include <stdio.h>

int main() {
    int i;
    for (i=0; i<10; i++) printf(".");
    return 0;
}

Output:

..........

In Python:

>>> for i in range(10): print('.')
.
.
.
.
.
.
.
.
.
.
>>> print('.', '.', '.', '.', '.', '.', '.', '.', '.', '.')
. . . . . . . . . .

In Python print will add a \n or space, how can I avoid that? Now, it’s just an example, don’t tell me I can first build a string then print it. I’d like to know how to “append” strings to stdout.


回答 0

在Python 3中,您可以使用函数的sep=end=参数print

不在字符串末尾添加换行符:

print('.', end='')

不在要打印的所有函数参数之间添加空格:

print('a', 'b', 'c', sep='')

您可以将任何字符串传递给任何一个参数,并且可以同时使用两个参数。

如果您在缓冲方面遇到麻烦,可以通过添加flush=True关键字参数来刷新输出:

print('.', end='', flush=True)

Python 2.6和2.7

在Python 2.6中,您可以print使用__future__模块从Python 3 导入函数:

from __future__ import print_function

允许您使用上面的Python 3解决方案。

但是,请注意,在从Python 2中导入flushprint函数的版本中,关键字不可用__future__;它仅适用于Python 3,更具体地说是3.3及更高版本。在早期版本中,您仍然需要通过调用进行手动刷新sys.stdout.flush()。您还必须在执行此导入操作的文件中重写所有其他打印语句。

或者你可以使用 sys.stdout.write()

import sys
sys.stdout.write('.')

您可能还需要调用

sys.stdout.flush()

确保stdout立即冲洗。

In Python 3, you can use the sep= and end= parameters of the print function:

To not add a newline to the end of the string:

print('.', end='')

To not add a space between all the function arguments you want to print:

print('a', 'b', 'c', sep='')

You can pass any string to either parameter, and you can use both parameters at the same time.

If you are having trouble with buffering, you can flush the output by adding flush=True keyword argument:

print('.', end='', flush=True)

Python 2.6 and 2.7

From Python 2.6 you can either import the print function from Python 3 using the __future__ module:

from __future__ import print_function

which allows you to use the Python 3 solution above.

However, note that the flush keyword is not available in the version of the print function imported from __future__ in Python 2; it only works in Python 3, more specifically 3.3 and later. In earlier versions you’ll still need to flush manually with a call to sys.stdout.flush(). You’ll also have to rewrite all other print statements in the file where you do this import.

Or you can use sys.stdout.write()

import sys
sys.stdout.write('.')

You may also need to call

sys.stdout.flush()

to ensure stdout is flushed immediately.


回答 1

它应该像Guido Van Rossum在此链接中描述的那样简单:

回复:没有AC / R的情况下如何打印?

http://legacy.python.org/search/hypermail/python-1992/0115.html

是否可以打印某些内容但不自动附加回车符?

是的,在要打印的最后一个参数之后附加一个逗号。例如,此循环在用空格分隔的一行上打印数字0..9。注意添加最后换行符的无参数“ print”:

>>> for i in range(10):
...     print i,
... else:
...     print
...
0 1 2 3 4 5 6 7 8 9
>>> 

It should be as simple as described at this link by Guido Van Rossum:

Re: How does one print without a c/r ?

http://legacy.python.org/search/hypermail/python-1992/0115.html

Is it possible to print something but not automatically have a carriage return appended to it ?

Yes, append a comma after the last argument to print. For instance, this loop prints the numbers 0..9 on a line separated by spaces. Note the parameterless “print” that adds the final newline:

>>> for i in range(10):
...     print i,
... else:
...     print
...
0 1 2 3 4 5 6 7 8 9
>>> 

回答 2

注意:这个问题的标题曾经是“如何在python中使用printf?”之类的东西。

由于人们可能会来这里根据标题进行查找,因此Python还支持printf样式的替换:

>>> strings = [ "one", "two", "three" ]
>>>
>>> for i in xrange(3):
...     print "Item %d: %s" % (i, strings[i])
...
Item 0: one
Item 1: two
Item 2: three

而且,您可以方便地将字符串值相乘:

>>> print "." * 10
..........

Note: The title of this question used to be something like “How to printf in python?”

Since people may come here looking for it based on the title, Python also supports printf-style substitution:

>>> strings = [ "one", "two", "three" ]
>>>
>>> for i in xrange(3):
...     print "Item %d: %s" % (i, strings[i])
...
Item 0: one
Item 1: two
Item 2: three

And, you can handily multiply string values:

>>> print "." * 10
..........

回答 3

对python2.6 +使用python3样式的打印功能 (还将破坏同一文件中任何现有的关键字打印语句。)

# for python2 to use the print() function, removing the print keyword
from __future__ import print_function
for x in xrange(10):
    print('.', end='')

要不破坏您的所有python2打印关键字,请创建一个单独的printf.py文件

# printf.py

from __future__ import print_function

def printf(str, *args):
    print(str % args, end='')

然后,在您的文件中使用它

from printf import printf
for x in xrange(10):
    printf('.')
print 'done'
#..........done

更多示例展示printf风格

printf('hello %s', 'world')
printf('%i %f', 10, 3.14)
#hello world10 3.140000

Use the python3-style print function for python2.6+ (will also break any existing keyworded print statements in the same file.)

# for python2 to use the print() function, removing the print keyword
from __future__ import print_function
for x in xrange(10):
    print('.', end='')

To not ruin all your python2 print keywords, create a separate printf.py file

# printf.py

from __future__ import print_function

def printf(str, *args):
    print(str % args, end='')

Then, use it in your file

from printf import printf
for x in xrange(10):
    printf('.')
print 'done'
#..........done

More examples showing printf style

printf('hello %s', 'world')
printf('%i %f', 10, 3.14)
#hello world10 3.140000

回答 4

如何在同一行上打印:

import sys
for i in xrange(0,10):
   sys.stdout.write(".")
   sys.stdout.flush()

How to print on the same line:

import sys
for i in xrange(0,10):
   sys.stdout.write(".")
   sys.stdout.flush()

回答 5

新功能(自Python 3.x起)print具有一个可选end参数,可用于修改结尾字符:

print("HELLO", end="")
print("HELLO")

输出:

你好你好

还有sep分隔符:

print("HELLO", "HELLO", "HELLO", sep="")

输出:

你好你好你好

如果您想在Python 2.x中使用它,只需在文件开头添加它:

from __future__ import print_function

The new (as of Python 3.x) print function has an optional end parameter that lets you modify the ending character:

print("HELLO", end="")
print("HELLO")

Output:

HELLOHELLO

There’s also sep for separator:

print("HELLO", "HELLO", "HELLO", sep="")

Output:

HELLOHELLOHELLO

If you wanted to use this in Python 2.x just add this at the start of your file:

from __future__ import print_function


回答 6

使用functools.partial创建一个名为printf的新函数

>>> import functools

>>> printf = functools.partial(print, end="")

>>> printf("Hello world\n")
Hello world

使用默认参数包装函数的简单方法。

Using functools.partial to create a new function called printf

>>> import functools

>>> printf = functools.partial(print, end="")

>>> printf("Hello world\n")
Hello world

Easy way to wrap a function with default parameters.


回答 7

您只需,print函数的末尾添加,这样它就不会在新行上打印。

You can just add , in the end of print function so it won’t print on new line.


回答 8

在Python 3+中,print是一个函数。您打电话的时候

print('hello world')

Python将其转换为

print('hello world', end='\n')

您可以更改end为所需的任何内容。

print('hello world', end='')
print('hello world', end=' ')

In Python 3+, print is a function. When you call

print('hello world')

Python translates it to

print('hello world', end='\n')

You can change end to whatever you want.

print('hello world', end='')
print('hello world', end=' ')

回答 9

python 2.6+

from __future__ import print_function # needs to be first statement in file
print('.', end='')

的Python 3

print('.', end='')

python <= 2.5

import sys
sys.stdout.write('.')

如果每次打印后多余的空间都可以,在python 2中

print '.',

在python 2中产生误导避免

print('.'), # avoid this if you want to remain sane
# this makes it look like print is a function but it is not
# this is the `,` creating a tuple and the parentheses enclose an expression
# to see the problem, try:
print('.', 'x'), # this will print `('.', 'x') `

python 2.6+:

from __future__ import print_function # needs to be first statement in file
print('.', end='')

python 3:

print('.', end='')

python <= 2.5:

import sys
sys.stdout.write('.')

if extra space is OK after each print, in python 2

print '.',

misleading in python 2 – avoid:

print('.'), # avoid this if you want to remain sane
# this makes it look like print is a function but it is not
# this is the `,` creating a tuple and the parentheses enclose an expression
# to see the problem, try:
print('.', 'x'), # this will print `('.', 'x') `

回答 10

你可以试试:

import sys
import time
# Keeps the initial message in buffer.
sys.stdout.write("\rfoobar bar black sheep")
sys.stdout.flush()
# Wait 2 seconds
time.sleep(2)
# Replace the message with a new one.
sys.stdout.write("\r"+'hahahahaaa             ')
sys.stdout.flush()
# Finalize the new message by printing a return carriage.
sys.stdout.write('\n')

You can try:

import sys
import time
# Keeps the initial message in buffer.
sys.stdout.write("\rfoobar bar black sheep")
sys.stdout.flush()
# Wait 2 seconds
time.sleep(2)
# Replace the message with a new one.
sys.stdout.write("\r"+'hahahahaaa             ')
sys.stdout.flush()
# Finalize the new message by printing a return carriage.
sys.stdout.write('\n')

回答 11

您可以在python3中执行以下操作:

#!usr/bin/python

i = 0
while i<10 :
    print('.',end='')
    i = i+1

并用python filename.py或执行python3 filename.py

You can do the same in python3 as follows :

#!usr/bin/python

i = 0
while i<10 :
    print('.',end='')
    i = i+1

and execute it with python filename.py or python3 filename.py


回答 12

我最近有同样的问题..

我通过做解决了:

import sys, os

# reopen stdout with "newline=None".
# in this mode,
# input:  accepts any newline character, outputs as '\n'
# output: '\n' converts to os.linesep

sys.stdout = os.fdopen(sys.stdout.fileno(), "w", newline=None)

for i in range(1,10):
        print(i)

这在Unix和Windows上都可以使用…尚未在macosx上对其进行测试…

hth

i recently had the same problem..

i solved it by doing:

import sys, os

# reopen stdout with "newline=None".
# in this mode,
# input:  accepts any newline character, outputs as '\n'
# output: '\n' converts to os.linesep

sys.stdout = os.fdopen(sys.stdout.fileno(), "w", newline=None)

for i in range(1,10):
        print(i)

this works on both unix and windows … have not tested it on macosx …

hth


回答 13

@lenooh满足了我的查询。我在搜索“ python抑制换行符”时发现了这篇文章。我在Raspberry Pi上使用IDLE3开发用于PuTTY的Python 3.2。我想在PuTTY命令行上创建一个进度条。我不希望页面滚动离开。我想要一条水平线来再次确保用户不会害怕该程序没有停顿下来,也没有在快乐的无限循环中被送去吃午饭-恳求“离开我,我做得很好,但这可能需要一些时间。” 交互式消息-类似于文本中的进度条。

print('Skimming for', search_string, '\b! .001', end='')初始化通过准备下一屏幕写,这将打印3退格作为⌫⌫⌫调刀混合法,然后一个周期,拭去“001”和延伸期间的行中的消息。之后search_string鹦鹉用户输入,\b!修剪我的惊叹号search_string文字背在其上的空间print(),否则的力量,正确放置标点符号。接下来是空格和我正在模拟的“进度条”的第一个“点”。然后,该消息也不必要地以页码填充(格式为长度为3的长度,前导零),以引起用户的注意,正在处理进度,这也将反映出我们稍后将构建的周期数对。

import sys

page=1
search_string=input('Search for?',)
print('Skimming for', search_string, '\b! .001', end='')
sys.stdout.flush() # the print function with an end='' won't print unless forced
while page:
    # some stuff…
    # search, scrub, and build bulk output list[], count items,
    # set done flag True
    page=page+1 #done flag set in 'some_stuff'
    sys.stdout.write('\b\b\b.'+format(page, '03')) #<-- here's the progress bar meat
    sys.stdout.flush()
    if done: #( flag alternative to break, exit or quit)
        print('\nSorting', item_count, 'items')
        page=0 # exits the 'while page' loop
list.sort()
for item_count in range(0, items)
    print(list[item_count])
#print footers here
 if not (len(list)==items):
    print('#error_handler')

进度栏处在sys.stdout.write('\b\b\b.'+format(page, '03'))排队状态。首先,要擦除到左侧,它会将光标备份到三个数字字符上,并以’\ b \ b \ b’作为⌫⌫⌫摩擦,并放下新的句点以增加进度条的长度。然后,它写入到目前为止的页面的三位数。由于sys.stdout.write()等待完整的缓冲区或输出通道关闭,因此sys.stdout.flush()强制立即写入。sys.stdout.flush()内置到末尾,print()而则绕过print(txt, end='' )。然后,代码循环执行其繁琐的时间密集型操作,同时不再打印任何内容,直到返回此处擦除三位数字,添加一个句点并再次写入三位数字(递增)。

擦拭和重写的三个数字是没有必要的手段-它只是一个蓬勃发展,其例证了sys.stdout.write()对比print()。您只需将周期条每次打印更长的时间,就可以很容易地给句号加注,而忘记三个花哨的反斜杠-b⌫退格键(当然也不会写入格式化的页数),而无需使用空格或换行符,而只需使用sys.stdout.write('.'); sys.stdout.flush()对。

请注意,Raspberry Pi IDLE3 Python外壳程序不将Backspace用作⌫rubout,而是打印一个空格,而是创建一个明显的分数列表。

-(o = 8> wiz

@lenooh satisfied my query. I discovered this article while searching for ‘python suppress newline’. I’m using IDLE3 on Raspberry Pi to develop Python 3.2 for PuTTY. I wanted to create a progress bar on the PuTTY command line. I didn’t want the page scrolling away. I wanted a horizontal line to re-assure the user from freaking out that the program hasn’t cruncxed to a halt nor been sent to lunch on a merry infinite loop – as a plea to ‘leave me be, I’m doing fine, but this may take some time.’ interactive message – like a progress bar in text.

The print('Skimming for', search_string, '\b! .001', end='') initializes the message by preparing for the next screen-write, which will print three backspaces as ⌫⌫⌫ rubout and then a period, wiping off ‘001’ and extending the line of periods. After search_string parrots user input, the \b! trims the exclamation point of my search_string text to back over the space which print() otherwise forces, properly placing the punctuation. That’s followed by a space and the first ‘dot’ of the ‘progress bar’ which I’m simulating. Unnecessarily, the message is also then primed with the page number (formatted to a length of three with leading zeros) to take notice from the user that progress is being processed and which will also reflect the count of periods we will later build out to the right.

import sys

page=1
search_string=input('Search for?',)
print('Skimming for', search_string, '\b! .001', end='')
sys.stdout.flush() # the print function with an end='' won't print unless forced
while page:
    # some stuff…
    # search, scrub, and build bulk output list[], count items,
    # set done flag True
    page=page+1 #done flag set in 'some_stuff'
    sys.stdout.write('\b\b\b.'+format(page, '03')) #<-- here's the progress bar meat
    sys.stdout.flush()
    if done: #( flag alternative to break, exit or quit)
        print('\nSorting', item_count, 'items')
        page=0 # exits the 'while page' loop
list.sort()
for item_count in range(0, items)
    print(list[item_count])
#print footers here
 if not (len(list)==items):
    print('#error_handler')

The progress bar meat is in the sys.stdout.write('\b\b\b.'+format(page, '03')) line. First, to erase to the left, it backs up the cursor over the three numeric characters with the ‘\b\b\b’ as ⌫⌫⌫ rubout and drops a new period to add to the progress bar length. Then it writes three digits of the page it has progressed to so far. Because sys.stdout.write() waits for a full buffer or the output channel to close, the sys.stdout.flush() forces the immediate write. sys.stdout.flush() is built into the end of print() which is bypassed with print(txt, end='' ). Then the code loops through its mundane time intensive operations while it prints nothing more until it returns here to wipe three digits back, add a period and write three digits again, incremented.

The three digits wiped and rewritten is by no means necessary – it’s just a flourish which exemplifies sys.stdout.write() versus print(). You could just as easily prime with a period and forget the three fancy backslash-b ⌫ backspaces (of course not writing formatted page counts as well) by just printing the period bar longer by one each time through – without spaces or newlines using just the sys.stdout.write('.'); sys.stdout.flush() pair.

Please note that the Raspberry Pi IDLE3 Python shell does not honor the backspace as ⌫ rubout but instead prints a space, creating an apparent list of fractions instead.

—(o=8> wiz


回答 14

您会注意到上述所有答案都是正确的。但是我想做一个捷径,总是总是在最后写入“ end =”参数。

你可以定义一个像

def Print(*args,sep='',end='',file=None,flush=False):
    print(*args,sep=sep,end=end,file=file,flush=flush)

它将接受所有数量的参数。即使它将接受所有其他参数,如file,flush等,并使用相同的名称。

You will notice that all the above answers are correct. But I wanted to make a shortcut to always writing the ” end=” ” parameter in the end.

You could define a function like

def Print(*args,sep='',end='',file=None,flush=False):
    print(*args,sep=sep,end=end,file=file,flush=flush)

It would accept all the number of parameters. Even it will accept all the other parameters like file, flush ,etc and with the same name.


回答 15

这些答案中的许多似乎有些复杂。在Python 3.x中,您只需执行以下操作:

print(<expr>, <expr>, ..., <expr>, end=" ")

end的默认值是"\n"。我们只是将其更改为空格,或者您也可以使用end=""(没有空格)执行printf通常的操作。

Many of these answers seem a little complicated. In Python 3.x you simply do this:

print(<expr>, <expr>, ..., <expr>, end=" ")

The default value of end is "\n". We are simply changing it to a space or you can also use end="" (no space) to do what printf normally does.


回答 16

您想在for循环中打印一些内容;但是您不希望它每次都在新行中打印..例如:

 for i in range (0,5):
   print "hi"

 OUTPUT:
    hi
    hi
    hi
    hi
    hi

但是您希望它像这样打印:嗨,嗨,嗨,嗨,嗨?只需在打印“ hi”后添加一个逗号

例:

for i in range (0,5): print "hi", OUTPUT: hi hi hi hi hi

you want to print something in for loop right;but you don’t want it print in new line every time.. for example:

 for i in range (0,5):
   print "hi"

 OUTPUT:
    hi
    hi
    hi
    hi
    hi

but you want it to print like this: hi hi hi hi hi hi right???? just add a comma after print “hi”

Example:

for i in range (0,5): print "hi", OUTPUT: hi hi hi hi hi


回答 17

或具有以下功能:

def Print(s):
   return sys.stdout.write(str(s))

那么现在:

for i in range(10): # or `xrange` for python 2 version
   Print(i)

输出:

0123456789

Or have a function like:

def Print(s):
   return sys.stdout.write(str(s))

Then now:

for i in range(10): # or `xrange` for python 2 version
   Print(i)

Outputs:

0123456789

回答 18

for i in xrange(0,10): print '\b.',

这在2.7.8和2.5.2(分别为Canopy和OSX终端)中都有效-不需要模块导入或时间旅行。

for i in xrange(0,10): print '\b.',

This worked in both 2.7.8 & 2.5.2 (Canopy and OSX terminal, respectively) — no module imports or time travel required.


回答 19

一般有两种方法可以做到这一点:

在Python 3.x中不使用换行符进行打印

在print语句之后不添加任何内容,并使用end='' as 删除’\ n’ :

>>> print('hello')
hello  # appending '\n' automatically
>>> print('world')
world # with previous '\n' world comes down

# solution is:
>>> print('hello', end='');print(' world'); # end with anything like end='-' or end=" " but not '\n'
hello world # it seem correct output

循环中的另一个示例

for i in range(1,10):
    print(i, end='.')

在Python 2.x中不使用换行符进行打印

添加结尾逗号表示打印后忽略\n

>>> print "hello",; print" world"
hello world

循环中的另一个示例

for i in range(1,10):
    print "{} .".format(i),

希望这会帮助你。您可以访问此链接

There are general two ways to do this:

Print without newline in Python 3.x

Append nothing after the print statement and remove ‘\n’ by using end='' as:

>>> print('hello')
hello  # appending '\n' automatically
>>> print('world')
world # with previous '\n' world comes down

# solution is:
>>> print('hello', end='');print(' world'); # end with anything like end='-' or end=" " but not '\n'
hello world # it seem correct output

Another Example in Loop:

for i in range(1,10):
    print(i, end='.')

Print without newline in Python 2.x

Adding a trailing comma says that after print ignore \n.

>>> print "hello",; print" world"
hello world

Another Example in Loop:

for i in range(1,10):
    print "{} .".format(i),

Hope this will help you. You can visit this link .


回答 20

…您不需要导入任何库。只需使用删除字符:

BS=u'\0008' # the unicode for "delete" character
for i in range(10):print(BS+"."),

这将删除换行符和空格(^ _ ^)*

…you do not need to import any library. Just use the delete character:

BS=u'\0008' # the unicode for "delete" character
for i in range(10):print(BS+"."),

this removes the newline and the space (^_^)*


声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。