【问题标题】:Print without a newline between two strings [duplicate]打印两个字符串之间没有换行符[重复]
【发布时间】:2023-03-19 09:27:01
【问题描述】:

我想在之前在 python 中打印过的另一个文本旁边打印一些文本 例如

print("Hello")
a="This is a test"
print(a)

我的意思是像这样打印“HelloThis is a test”而不是在下一行我知道我应该使用 print("Hello",a) 但我想使用单独的打印命令!!!!

【问题讨论】:

  • print("Hello%s" % a)也可以
  • 或 print("Hello{}.format(a)) 使用新的(首选).format 语法。

标签: python text python-3.x printing


【解决方案1】:

在第一个print 调用中使用end=''

print("Hello", end='')
a = "This is a test"
print(a)
#HelloThis is a test

求助print:

print(value, ..., sep=' ', end='\n', file=sys.stdout)

Prints the values to a stream, or to sys.stdout by default.
Optional keyword arguments:
file: a file-like object (stream); defaults to the current sys.stdout.
sep:  string inserted between values, default a space.
end:  string appended after the last value, default a newline.

【讨论】:

  • 这只适用于Python-3.x
  • @dansalmo 问题上有一个 python-3.x 标签。
  • 问题上还有一个Python标签。
  • @dansalmo:FWIW,推荐的策略是使用Python 指定语言和版本标签来指定您使用的方言。所以给定标签python python-3.x,答案通常应该是3。有时提问者会弄错,通常是因为他们没有猜测到差异是相关的,但如果是这样,则应该修复标签。
  • @dansalmo 如果您在文件顶部添加from __future__ import print_function,这适用于python 2.6 和python 2.7。
【解决方案2】:

如果您使用的是 python 2.7(有问题的 python 标记),您可以在打印后放置一个逗号以不返回新行。

print("hello"),
print("world")

将一行一行地打印“helloworld”。 因此,在您的情况下,它将是:

print("Hello"),
print(a)

或者如果你使用 python 3(python3.x 标签有问题)使用:

print("hello", end='')
print('world')

所以你的情况是:

print("Hello", end='')
print(a)

【讨论】:

  • 不在 Python 3.x 中,这是他正在使用的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-04-14
  • 2014-04-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多