3

可能重复:
如何在没有换行符或空格的情况下在 Python 中打印?
如何在Python中不包含'\ n'打印字符串

我有一个看起来像这样的代码:

  print 'Going to %s'%href
            try:
                self.opener.open(self.url+href)
                print 'OK'

当我执行它时,我明显得到两行:

Going to mysite.php
OK

但想要的是:

Going to mysite.php OK
4

3 回答 3

5
>>> def test():
...    print 'let\'s',
...    pass
...    print 'party'
... 
>>> test()
let's party
>>> 

对于您的示例:

# note the comma at the end
print 'Going to %s' % href,
try:
   self.opener.open(self.url+href)
   print 'OK'
except:
   print 'ERROR'

print 语句末尾的逗号指示不要添加'\n'换行符。

我认为这个问题是针对 python 2.x 的,因为print它被用作语句。对于 python 3,您需要指定end=''print 函数调用:

# note the comma at the end
print('Going to %s' % href, end='')
try:
   self.opener.open(self.url+href)
   print(' OK')
except:
   print(' ERROR')
于 2012-10-13T22:45:16.730 回答
2

在 python3 中,您必须将end参数(默认为\n)设置为空字符串:

print('hello', end='')

http://docs.python.org/py3k/library/functions.html#print

于 2012-10-13T23:16:29.187 回答
1

在你的第一个结尾使用逗号print: -

print 'Going to %s'%href, 
于 2012-10-13T22:44:08.057 回答