[英]How do I put a space between two string items in Python
>>> 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任何帮助,将不胜感激
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))
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).对于元素的动态计数,您可以使用 join (就像在胎面中的另一个答案中一样)。
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
Update: since f-strings were introduced in Python 3.6, it is also possible to use them:更新:由于 f 字符串是在 Python 3.6 中引入的,因此也可以使用它们:
f'{item1} {item2}'
只需添加空间!
print(item1 + ' ' + item2)
# works every time
print(item1, item2)
# Only works if items 1 & 2 are strings.
print(item1 + " " + item2)
Here are three easy solutions to add a space.以下是添加空格的三个简单解决方案。
Add a space in between, but as noted above this only works if both items are strings.在两者之间添加一个空格,但如上所述,这仅在两个项目都是字符串时才有效。
print("eggs" + " " + "sandwich")
Another simple solution would be to add a space to end of eggs or beginning of sandwich.另一个简单的解决方案是在鸡蛋的末尾或三明治的开头添加一个空格。
print("eggs " + "sandwich")
print("eggs" + " sandwich")
These will all return the same result.这些都将返回相同的结果。
There are a lot of ways;):有很多方法;):
print(f'Hello {firstname} {lastname}')
Or或者
print("Hello", firstname, lastname)
Or或者
print("Hello", firstname + ' ' + lastname)
Or或者
print(' '.join(["Hello", firstname , lastname]))
Or或者
[print(i, end=' ') for i in ["Hello", firstname, lastname]]
How to add spaces between two concatenated strings?如何在两个连接的字符串之间添加空格? ****Here you got answer for the above question.** **I think so this is simple way to add spaces between two concatenated strings.**** ****这里你得到了上述问题的答案。** **我认为这是在两个连接字符串之间添加空格的简单方法。****
college ='geethanjaliinstituteofscienceandtechnology'
name =" " 'jaanu'
test1 =college+name
print(test1)
output:geethanjaliinstituteofscienceandtechnology jaanu输出:geethanjaliinstituteofscienceandtechnologyjaanu
#我遇到了同样的情况,这对我有用,如果它只是打印功能。#
`print(item1, item2)`
>>> item1="eggs"
>>> item2="sandwich"
>>> print(f"{item1} {item2}")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.