0

对不起这个可怕的标题!我不知道该写什么,而没有使瓷砖长 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 ]

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

4

7 回答 7

5

在 Python 2.x 中, whereprint是 statement,添加尾随逗号:

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

在 Python 3.x 中, whereprint()是一个普通函数end而不是语句,为关键字参数传递一个空字符串:

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

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

于 2013-07-31T21:05:08.463 回答
4

使用尾随逗号,这将抑制 . 之后添加的换行符print。签出print声明

print 'Hi!',
print 'How are you?'
于 2013-07-31T21:00:33.550 回答
2

使用逗号:

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

于 2013-07-31T21:04:59.893 回答
2

在语句末尾添加一个逗号:

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

输出:

Hi! How are you?

这是来自文档

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

于 2013-07-31T21:03:06.517 回答
2

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

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

这将输出:

Hi! How are you?     

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

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

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

于 2013-07-31T21:04:25.173 回答
1

在 Python3 中:

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

我猜是你在找什么!:texttext

您还可以设置分隔符:

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

给出:texttexttext而不是text text text

于 2013-07-31T21:00:03.220 回答
1

您也可以将所有字符串放在一个字符串中,如下所示:

>>> string = 'abc' + 'def'
>>> print string
'abcdef'
于 2013-07-31T21:04:28.563 回答