如何在Python中的两个字符串项之间放置一个空格

时间:2022-05-10 11:17:32
>>> item1="eggs"
>>> item2="sandwich"

>>> print(item1+item2)

>>> Output: eggssandwich

My main goal is to put a space between eggs and sandwich.

我的主要目标是在鸡蛋和三明治之间留一个空间。

But i'm unsure on how to. Any help would be appreciated

但我不确定如何。任何帮助,将不胜感激

3 个解决方案

#1


7  

Use .join():

使用.join():

print(" ".join([item1, item2]))

The default for print, however, is to put a space between arguments, so you could also do:

但是,print的默认设置是在参数之间放置一个空格,因此您也可以这样做:

print(item1, item2)

Another way would be to use string formatting:

另一种方法是使用字符串格式:

print("{} {}".format(item1, item2))

Or the old way:

或旧的方式:

print("%s %s" % (item1, item2))

#2


6  

Simply!

只是!

'{} {}'.format(item1, item2)  # the most prefereable

or

要么

'%s %s' % (item1, item2)

or if it is just print

或者如果它只是打印

print(item1, item2)

for dynamic count of elements you can use join(like in another answer in the tread).

对于元素的动态计数,您可以使用连接(如在胎面中的另一个答案)。

Also you can read how to make really flexible formatting using format language from the first variant in official documentation: https://docs.python.org/2/library/string.html#custom-string-formatting

您还可以阅读如何使用官方文档中第一个变体的格式语言进行非常灵活的格式化:https://docs.python.org/2/library/string.html#custom-string-formatting

#3


1  

Just add the space!

只需添加空间!

print(item1 + ' ' + item2)

#1


7  

Use .join():

使用.join():

print(" ".join([item1, item2]))

The default for print, however, is to put a space between arguments, so you could also do:

但是,print的默认设置是在参数之间放置一个空格,因此您也可以这样做:

print(item1, item2)

Another way would be to use string formatting:

另一种方法是使用字符串格式:

print("{} {}".format(item1, item2))

Or the old way:

或旧的方式:

print("%s %s" % (item1, item2))

#2


6  

Simply!

只是!

'{} {}'.format(item1, item2)  # the most prefereable

or

要么

'%s %s' % (item1, item2)

or if it is just print

或者如果它只是打印

print(item1, item2)

for dynamic count of elements you can use join(like in another answer in the tread).

对于元素的动态计数,您可以使用连接(如在胎面中的另一个答案)。

Also you can read how to make really flexible formatting using format language from the first variant in official documentation: https://docs.python.org/2/library/string.html#custom-string-formatting

您还可以阅读如何使用官方文档中第一个变体的格式语言进行非常灵活的格式化:https://docs.python.org/2/library/string.html#custom-string-formatting

#3


1  

Just add the space!

只需添加空间!

print(item1 + ' ' + item2)