Python 3.x 在python3中简单地在变量之间添加空格

Python 3.x 在python3中简单地在变量之间添加空格,python-3.x,Python 3.x,我搜索了一下,但找到了许多可以腾出空间的东西。我是python的新手,尝试编写一个简单的程序,询问名字、姓氏,然后打招呼。无论我在print函数行的name+last之间加了多少空格,它都会将名字和姓氏混合在一起 name = input ("What is your first name?: ") last = input ("what is your last name?: ") print ('Nice to meet you,' name + last) 它输出: 你的名字是什么?

我搜索了一下,但找到了许多可以腾出空间的东西。我是python的新手,尝试编写一个简单的程序,询问名字、姓氏,然后打招呼。无论我在print函数行的name+last之间加了多少空格,它都会将名字和姓氏混合在一起

name = input ("What is your first name?: ")

last = input ("what is your last name?: ")

print ('Nice to meet you,' name + last)
它输出:

你的名字是什么?:杰西

你姓什么?:杰克逊

很高兴认识你,杰西·杰克逊


我做错了什么?

您可以使用
+
附加包含以下空格的字符串文字:

print ('Nice to meet you, ' + name + ' ' + last)

如果不需要将它们连接在一起,可以使用:

print("Nice to meet you, " name, last)
输出:

很高兴认识你,杰西·杰克逊


这是因为
+
连接字符串,但
将它们打印在同一行上,但会自动将它们隔开,因为它们是独立的实体。

有几种方法可以获得所需的输出:

集中字符串
如果要集中字符串,请使用
+
运算符。
它将按照您在代码中提供字符串的方式来集中字符串。
示例:

>>> stringA = 'This is a'
>>> stringB = 'test'
>>> print(stringA + stringB)
'This is atest'

>>> print(stringA + ' ' + stringB)
'This is a test'
>>> print('I want to say:', stringA, stringB)
I want to say: This is a test
>>> print('Format {} example {}'.format(stringA, stringB))
Format This is a example test

>>> print('Old: %s example %s of string formatting' % (stringA, stringB))
Old: This is a example test of string formatting
在同一行上打印

如果您只想在同一行上打印多个字符串,您可以将字符串作为参数提供给
print
函数,并用
分隔
示例:

>>> stringA = 'This is a'
>>> stringB = 'test'
>>> print(stringA + stringB)
'This is atest'

>>> print(stringA + ' ' + stringB)
'This is a test'
>>> print('I want to say:', stringA, stringB)
I want to say: This is a test
>>> print('Format {} example {}'.format(stringA, stringB))
Format This is a example test

>>> print('Old: %s example %s of string formatting' % (stringA, stringB))
Old: This is a example test of string formatting
格式化字符串

最常用的方法是字符串格式。这可以通过两种方式完成:
-使用
格式
功能
-对
%s

使用“旧”方式 示例:

>>> stringA = 'This is a'
>>> stringB = 'test'
>>> print(stringA + stringB)
'This is atest'

>>> print(stringA + ' ' + stringB)
'This is a test'
>>> print('I want to say:', stringA, stringB)
I want to say: This is a test
>>> print('Format {} example {}'.format(stringA, stringB))
Format This is a example test

>>> print('Old: %s example %s of string formatting' % (stringA, stringB))
Old: This is a example test of string formatting
当然,这些示例可以以任何方式组合。
示例:

>>> stringC = 'normally'
>>> print((('%s strange {} no one ' % stringA) + stringC).format(stringB), 'uses')
This is a strange test no one normally uses

谢谢你抽出时间!啊,我没想到这么简单。我想我必须使用+。我现在觉得很傻,非常感谢你的详细回复。我不知道为什么我脑子里会有这样的想法:我必须将字符串串联起来,而不是仅仅将它们打印在同一行上。我真的很感谢你花时间回复抱歉,在我发布这篇文章后,我们出人意料地出城了。