And*_*mbu 1760 python newline python-2.x
问题出在标题中.
我想在python中做到这一点 .我想在c中的这个例子中做些什么:
#include <stdio.h>
int main() {
int i;
for (i=0; i<10; i++) printf(".");
return 0;
}
Run Code Online (Sandbox Code Playgroud)
输出:
..........
Run Code Online (Sandbox Code Playgroud)
在Python中:
>>> for i in xrange(0,10): print '.'
.
.
.
.
.
.
.
.
.
.
>>> for i in xrange(0,10): print '.',
. . . . . . . . . .
Run Code Online (Sandbox Code Playgroud)
在Python中print
会添加一个\n
或一个空格,我该如何避免呢?现在,这只是一个例子.不要告诉我,我可以先构建一个字符串然后打印它.我想知道如何"附加"字符串stdout
.
cod*_*gic 2387
import sys
sys.stdout.write('.')
Run Code Online (Sandbox Code Playgroud)
您可能还需要打电话
sys.stdout.flush()
Run Code Online (Sandbox Code Playgroud)
确保stdout
立即冲洗.
从Python 2.6,您可以print
从Python 3 导入该函数:
from __future__ import print_function
Run Code Online (Sandbox Code Playgroud)
这允许您使用下面的Python 3解决方案.
在Python 3中,print
语句已更改为函数.在Python 3中,您可以改为:
print('.', end='')
Run Code Online (Sandbox Code Playgroud)
这也适用于Python 2,前提是您已经使用过from __future__ import print_function
.
如果遇到缓冲问题,可以通过添加flush=True
关键字参数来刷新输出:
print('.', end='', flush=True)
Run Code Online (Sandbox Code Playgroud)
但请注意,在Python 2中导入flush
的print
函数版本中没有该关键字__future__
; 它只适用于Python 3,更具体地说是3.3及更高版本.在早期版本中,您仍然需要通过调用手动刷新sys.stdout.flush()
.
小智 294
它应该像Guido Van Rossum在这个链接中所描述的那样简单:
Re:如何在没有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
>>>
Run Code Online (Sandbox Code Playgroud)
Bea*_*eau 164
注意:这个问题的标题曾经是"如何在python中打印?"
由于人们可能会根据标题来到这里寻找它,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
Run Code Online (Sandbox Code Playgroud)
并且,您可以轻松地乘以字符串值:
>>> print "." * 10
..........
Run Code Online (Sandbox Code Playgroud)
k10*_*107 91
对python2.6 +使用python3样式的打印函数 (也会破坏同一文件中任何现有的keyworded打印语句.)
# for python2 to use the print() function, removing the print keyword
from __future__ import print_function
for x in xrange(10):
print('.', end='')
Run Code Online (Sandbox Code Playgroud)
若要不破坏所有python2打印关键字,请创建单独的printf.py
文件
# printf.py
from __future__ import print_function
def printf(str, *args):
print(str % args, end='')
Run Code Online (Sandbox Code Playgroud)
然后,在您的文件中使用它
from printf import printf
for x in xrange(10):
printf('.')
print 'done'
#..........done
Run Code Online (Sandbox Code Playgroud)
更多示例显示printf样式
printf('hello %s', 'world')
printf('%i %f', 10, 3.14)
#hello world10 3.140000
Run Code Online (Sandbox Code Playgroud)
len*_*ooh 39
这不是标题中问题的答案,但它是关于如何在同一行上打印的答案:
import sys
for i in xrange(0,10):
sys.stdout.write(".")
sys.stdout.flush()
Run Code Online (Sandbox Code Playgroud)
Sil*_*ost 27
新的(从Python 3.0开始)print
函数有一个可选end
参数,允许您修改结束字符.还有sep
分隔符.
小智 20
使用functools.partial创建一个名为printf的新函数
>>> import functools
>>> printf = functools.partial(print, end="")
>>> printf("Hello world\n")
Hello world
Run Code Online (Sandbox Code Playgroud)
使用默认参数包装函数的简便方法.
use*_*437 16
您可以添加功能,
的末尾,print
以便它不会在新行上打印.
小智 11
在Python 3中,打印是一种功能.你打电话的时候
print('hello world')
Run Code Online (Sandbox Code Playgroud)
Python将其翻译为
print('hello world', end='\n')
Run Code Online (Sandbox Code Playgroud)
您可以将结束更改为您想要的任何内容.
print('hello world', end='')
print('hello world', end=' ')
Run Code Online (Sandbox Code Playgroud)
sus*_*097 10
一般来说,有两种方法可以做到这一点:
Python 3.x 中不带换行符的打印
在 print 语句后不添加任何内容,并使用 , 删除 '\n' end=''
,如下所示:
>>> print('hello')
hello # Appending '\n' automatically
>>> print('world')
world # With previous '\n' world comes down
# The solution is:
>>> print('hello', end='');print(' world'); # End with anything like end='-' or end=" ", but not '\n'
hello world # It seems to be the correct output
Run Code Online (Sandbox Code Playgroud)
循环中的另一个例子:
for i in range(1,10):
print(i, end='.')
Run Code Online (Sandbox Code Playgroud)
Python 2.x 中不带换行符的打印
添加尾随逗号表示:打印后,忽略\n
。
>>> print "hello",; print" world"
hello world
Run Code Online (Sandbox Code Playgroud)
循环中的另一个例子:
for i in range(1,10):
print "{} .".format(i),
Run Code Online (Sandbox Code Playgroud)
您可以访问此链接。
小智 9
只需使用end=''
for i in range(5):
print('a',end='')
# aaaaa
Run Code Online (Sandbox Code Playgroud)
你可以试试:
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')
Run Code Online (Sandbox Code Playgroud)
只需使用end
="" 或sep
=""
>>> for i in range(10):
print('.', end = "")
Run Code Online (Sandbox Code Playgroud)
输出:
.........
Run Code Online (Sandbox Code Playgroud)
python 2.6+:
from __future__ import print_function # needs to be first statement in file
print('.', end='')
Run Code Online (Sandbox Code Playgroud)
的Python 3:
print('.', end='')
Run Code Online (Sandbox Code Playgroud)
python <= 2.5:
import sys
sys.stdout.write('.')
Run Code Online (Sandbox Code Playgroud)
如果每次打印后多余的空间都可以,在python 2中
print '.',
Run Code Online (Sandbox Code Playgroud)
在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') `
Run Code Online (Sandbox Code Playgroud)
小智 6
我最近遇到了同样的问题..
我解决了这个问题:
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)
Run Code Online (Sandbox Code Playgroud)
这适用于unix和windows ......还没有在macosx上测试过...
心连心
您可以在python3中执行以下操作:
#!usr/bin/python
i = 0
while i<10 :
print('.',end='')
i = i+1
Run Code Online (Sandbox Code Playgroud)
并用python filename.py
或执行python3 filename.py
小智 5
lenooh满足了我的询问。我在搜索“python抑制换行符”时发现了这篇文章。我正在 Raspberry Pi 上使用IDLE\xc2\xa03为PuTTY开发 Python 3.2 。
\n我想在 PuTTY 命令行上创建一个进度条。我不希望页面滚走。我想要一条水平线来安抚用户,以免他们惊慌失措,因为程序没有停止运行,也没有在快乐的无限循环中被发送去吃午饭——以此恳求“别打扰我,我做得很好” ,但这可能需要一些时间。\' 交互式消息 - 就像文本中的进度条。
\n通过准备下一个屏幕写入来初始化print(\'Skimming for\', search_string, \'\\b! .001\', end=\'\')
消息,这将打印三个退格键 \xe2\x8c\xab\xe2\x8c\xab\xe2\x8c\xab 擦除,然后打印一个句点,擦除 \'001\'并延长周期线。
search_string
鹦鹉学舌用户输入后,\\b!
修剪我的文本的感叹号search_string
以返回到空格print()
,否则会强制正确放置标点符号。接下来是一个空格和我正在模拟的“进度条”的第一个“点”。
不必要的是,该消息还带有页码(格式为长度为 3、前导零),以便用户注意到正在处理的进度,并且这也将反映我们稍后将构建到的周期计数。正确的。
\nimport sys\n\npage=1\nsearch_string=input(\'Search for?\',)\nprint(\'Skimming for\', search_string, \'\\b! .001\', end=\'\')\nsys.stdout.flush() # the print function with an end=\'\' won\'t print unless forced\nwhile page:\n # some stuff\xe2\x80\xa6\n # search, scrub, and build bulk output list[], count items,\n # set done flag True\n page=page+1 #done flag set in \'some_stuff\'\n sys.stdout.write(\'\\b\\b\\b.\'+format(page, \'03\')) #<-- here\'s the progress bar meat\n sys.stdout.flush()\n if done: #( flag alternative to break, exit or quit)\n print(\'\\nSorting\', item_count, \'items\')\n page=0 # exits the \'while page\' loop\nlist.sort()\nfor item_count in range(0, items)\n print(list[item_count])\n\n#print footers here\nif not (len(list)==items):\n print(\'#error_handler\')\n
Run Code Online (Sandbox Code Playgroud)\n进度条肉在排队sys.stdout.write(\'\\b\\b\\b.\'+format(page, \'03\'))
。首先,要向左擦除,它将光标备份到三个数字字符上,其中 \'\\b\\b\\b\' 为 \xe2\x8c\xab\xe2\x8c\xab\xe2\x8c \xab 删除并删除一个新句点以添加进度条长度。然后它会写入目前为止已前进到的页面的三位数字。因为sys.stdout.write()
等待缓冲区已满或输出通道关闭,所以sys.stdout.flush()
强制立即写入。sys.stdout.flush()
内置于其末端print()
,并用 绕过print(txt, end=\'\' )
。然后,代码循环执行日常的时间密集型操作,同时不再打印任何内容,直到返回此处擦除三位数字,添加句点并再次写入三位数字(递增)。
擦除和重写的三位数字根本没有必要——这只是一个华丽的例子,说明了sys.stdout.write()
与 的关系print()
。您可以轻松地用句号打底,然后忘记三个奇特的反斜杠-b \xe2\x8c\xab 退格键(当然也不要写入格式化的页数),只需每次将句号栏加长一号即可 - 不带空格或仅使用该sys.stdout.write(\'.\'); sys.stdout.flush()
对的换行符。
请注意,Raspberry Pi IDLE 3 Python shell 不将退格键视为 \xe2\x8c\xab rubout,而是打印一个空格,从而创建一个明显的分数列表。
\n小智 5
你想在for循环中正确打印一些东西;但你不希望它每次都以新行打印......
例如:
for i in range (0,5):
print "hi"
OUTPUT:
hi
hi
hi
hi
hi
Run Code Online (Sandbox Code Playgroud)
但是你希望它像这样打印:嗨嗨嗨嗨嗨对吗????
只需在打印“hi”后添加一个逗号。
例子:
for i in range (0,5):
print "hi",
Run Code Online (Sandbox Code Playgroud)
输出:
for i in range (0,5):
print "hi"
OUTPUT:
hi
hi
hi
hi
hi
Run Code Online (Sandbox Code Playgroud)
小智 5
许多这些答案似乎有点复杂。在 Python 3.x 中,您只需执行以下操作:
print(<expr>, <expr>, ..., <expr>, end=" ")
Run Code Online (Sandbox Code Playgroud)
end 的默认值为"\n"
。我们只是将其更改为空格,或者您也可以使用end=""
(无空格)来执行printf
通常的操作。
小智 5
您会注意到上述所有答案都是正确的。但是我想做一个捷径,总是总是在最后写入“ end =”参数。
你可以定义一个像
def Print(*args,sep='',end='',file=None,flush=False):
print(*args,sep=sep,end=end,file=file,flush=flush)
Run Code Online (Sandbox Code Playgroud)
它将接受所有数量的参数。即使它将接受所有其他参数,如file,flush等,并且使用相同的名称。