【问题标题】:Get two strings of text on the same line?在同一行获取两个文本字符串?
【发布时间】:2013-07-31 20:57:52
【问题描述】:

对不起这个糟糕的标题!我不知道该写什么,但没有使磁贴 500 字长。

假设我有

print 'Hi!'
print 'How are you?'

有什么办法可以把它放在同一行吗? “嗨!你好吗?”

这是我目前使用的代码:

choice = raw_input('>: ')
if choice=='1':
    menu1()
else:
    print '' +choice
    print 'is not a recognized commando.'

我的另一个代码是:

from colorama import Fore, Back, Style
print
print 'Now chatting with Tom'
time.sleep(2)
print
print
print(Fore.RED + 'Tom >: ') + print(Fore.GREEN + 'test')

这当然没有用。我只是想测试一下。

有什么办法可以把这两个字符串放到同一行吗?

非常感谢!

编辑:

非常感谢大家!我知道 Python 最基本的部分,但我不知道如何忽略 ,

无论如何。出于某种原因,我得到了额外的空间。我想写 [12:41:39](时间)。在我的代码中,它看起来像这样:

print(Fore.YELLOW + '['),
print strftime("%H:%M:%S"),
print ']          ',

输出是 [ 12:41:39 ]

我不知道这里出了什么问题。我真的希望这里有人可以为我解释一下!谢谢!

【问题讨论】:

  • 您使用的是 Python 2 还是 3?
  • 只是猜测,但看起来他使用的是 Python 2.x,因为他的 prints 没有括号。
  • 我使用的是 Python 2.7 感觉比 Python 3 更舒服。

标签: python string text


【解决方案1】:

在 Python 2.x 中,print is a statement 的位置添加一个尾随逗号:

print 'Hi!',  # No newline will be printed

在 Python 3.x 中,print() is an ordinary function 不是语句,而是为 end 关键字参数传递一个空字符串:

print('Hi!', end='')

如果您在 Python 2.x 代码中使用 from __future__ import print_function 来实现前向兼容性,那么您需要使用函数版本而不是语句版本。

【讨论】:

  • 感谢您提供的信息!正如 thegrinner 所说,我使用的是 Python 2.7,因为我觉得它比 3 更舒适。出于某种原因,当我这样做时,我得到了额外的空间。我已经更新了我的帖子,您可以在其中看到我的新代码,并希望找出问题所在。谢谢!
【解决方案2】:

使用尾随逗号,这将抑制在print 之后添加的换行符。查看print statement:

print 'Hi!',
print 'How are you?'

【讨论】:

    【解决方案3】:

    在语句末尾添加逗号:

    print 'Hi!',
    print 'How are you?'
    

    输出:

    Hi! How are you?
    

    这是来自documentation

    '\n' 字符写在末尾,除非print 语句以逗号结尾

    【讨论】:

      【解决方案4】:

      使用逗号:

      print 'Hi!', 'How are you?'

      【讨论】:

        【解决方案5】:

        在 python 2.x 中,您可以在 print 语句后使用逗号

        print 'Hi!',
        print 'How are you?'
        

        将输出:

        Hi! How are you?     
        

        您也可以从 python 3.x 导入print 函数并执行

        from __future__ import print_function
        print("Hi!", end='')
        

        这会将一个空字符串作为结束字符而不是 \n

        【讨论】:

          【解决方案6】:

          在 Python3 中:

          print('text', end='')
          print('text', end='')
          

          我猜这就是你要找的东西! :texttext

          也可以设置分隔符:

          print('text', 'text', 'text', sep = '')
          

          提供:texttexttext 而不是 text text text

          【讨论】:

          • 只是猜测,但看起来他使用的是 Python 2.x,因为他的 prints 没有括号。
          【解决方案7】:

          你也可以像这样把你所有的字符串放在一个字符串中:

          >>> string = 'abc' + 'def'
          >>> print string
          'abcdef'
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2016-10-27
            • 1970-01-01
            • 2017-09-13
            • 1970-01-01
            • 1970-01-01
            • 2013-04-02
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多