【问题标题】:how to print string at the end of the previous string Python [duplicate]如何在上一个字符串Python的末尾打印字符串[重复]
【发布时间】:2012-10-04 08:49:46
【问题描述】:

可能重复:
How to print in Python without newline or space?
How to print a string without including ‘\n’ in Python

我的代码如下所示:

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

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

Going to mysite.php
OK

但想要的是:

Going to mysite.php OK

【问题讨论】:

    标签: python string


    【解决方案1】:
    >>> 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 语句的comma at the end 指示不要添加'\n' 换行符。

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

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

    【讨论】:

    【解决方案2】:

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

    print('hello', end='')
    

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

    【讨论】:

      【解决方案3】:

      在您的第一个 print 末尾使用逗号:-

      print 'Going to %s'%href, 
      

      【讨论】:

        猜你喜欢
        • 2014-09-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-03-21
        • 1970-01-01
        • 2019-02-19
        • 1970-01-01
        相关资源
        最近更新 更多