Python中print输出多个内容报错,如何正确实现?
Python print输出多个内容的语法修正
你的代码第3行print(hello world)出现语法错误,原因是Python不允许在函数参数里直接用空格连接变量,必须用正确的方式组合或分隔多个内容。以下是几种能实现你需求(输出Hello world!)的修正方案:
方案1:用逗号分隔参数(最简洁)
Python的print()函数支持传入多个参数,默认会在参数之间添加空格,末尾自动换行:
hello = "Hello" #make hello "hello" world = "world!" #make world "world!" print(hello, world) #print hello world
方案2:字符串拼接
通过+号将字符串和变量拼接,注意需要手动添加空格来分隔内容:
hello = "Hello" #make hello "hello" world = "world!" #make world "world!" print(hello + " " + world) #print hello world
方案3:使用f-string(Python3.6+推荐)
f-string可以直接将变量嵌入字符串中,格式清晰易读:
hello = "Hello" #make hello "hello" world = "world!" #make world "world!" print(f"{hello} {world}") #print hello world
以上三种方式都能输出你期望的Hello world!,根据实际场景选择即可。
内容的提问来源于stack exchange,提问作者python fan
相关产品推荐
相关产品推荐

