Python 2.7.8打印为一行,不带逗号
我一直收到相同的错误消息,但我不知道错误是想告诉我什么Python 2.7.8打印为一行,不带逗号,python,debugging,Python,Debugging,我一直收到相同的错误消息,但我不知道错误是想告诉我什么 # from __future__ import print_function from sys import argv from os.path import exists # unpack the arguments filename = argv print("Checking if %s exists" % filename, sep='', end='') 这里是错误 SyntaxError: invalid syntax
# from __future__ import print_function
from sys import argv
from os.path import exists
# unpack the arguments
filename = argv
print("Checking if %s exists" % filename, sep='', end='')
这里是错误
SyntaxError: invalid syntax
File "check.py", line 8
print("Checking if %s exists" % filename, sep='', end='')
^
根据上下文,语法看起来是正确的。我尝试过删除括号,我尝试过导入未来打印函数,希望这能有所帮助。我不知道还能做什么。谢谢你的帮助,整个程序如下
# Program checks if file exists. Prints out textual interface
# gives the impression of "loading".
from __future__ import print_function
from sys import argv
from os.path import exists
from time import sleep
# unpack the arguments
script, filename = argv
print("Checking if %s exists" % filename, sep='', end='')
for i in range(2):
for j in range(3):
sleep(1)
print( ".", sep='', end='')
print( "\b\b\b", sep='', end='')
print
print("File exists: %s" % exists(filename) )
尝试:
我不完全确定您使用的是什么sep='
和end='
[编辑:修复缺少的双引号]您有几个选项,但需要正确使用它们 首先,如果使用来自未来导入打印功能的
,,则必须为打印()使用父项。这种导入将Python2的print
更改为与Python3版本相同。这仅适用于Python2.x解释器。当然,Python3已经有了print()
在print
末尾添加逗号仅适用于Python 2.x样式的print
。对于Python3样式的print()
,它没有意义
记住这一点,你有两个选择
Python3样式:print(“一些文本”,end='')
使用sys.stdout
:sys.stdout.write(“一些文本”)
这两个选项在Python2.7(使用来自未来导入打印功能的)和Python3中工作
from __future__ import print_function
import sys
def print_no_newline_1(text):
sys.stdout.write("the text is [%s]" % text)
def python3_style(text):
print("the text is [%s]" % text, end='')
if __name__ == '__main__':
print_no_newline_1("my text")
print(" this will be on the same line")
python3_style("my text")
print(" this will be on the same line")
下面的示例包括您正在使用的%s”%X
。还要注意的是,在Python3中,这种样式已经被弃用了
from __future__ import print_function
import sys
def print_no_newline_1(text):
sys.stdout.write("the text is [%s]" % text)
def python3_style(text):
print("the text is [%s]" % text, end='')
if __name__ == '__main__':
print_no_newline_1("my text")
print(" this will be on the same line")
python3_style("my text")
print(" this will be on the same line")
在Python 2和Python 3中,此脚本的输出为:
the text is [my text] this will be on the same line
the text is [my text] this will be on the same line
你确定吗?你的代码适合我(如果我取消注释第一行的话)。不相关,但是filename=argv
可能不会像你期望的那样“解包参数”。哦,谢谢。我想我在那里惊慌失措了。这不是整个计划。我拿出了一个不相关的部分来发布这个问题。你的完整程序对我也适用(我运行的是Python 2.7.6)。我的一个建议是对倒数第二行执行print()
,而不是print
。后者什么也不做,前者打印一个换行符。这是Python 3的东西。这是我想的,因为他的语法是Python 3。我以前从未见过它。