You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python使用+拼接字符串传入print函数输出无空格,如何添加间隔空格?

问题原因

用+运算符拼接字符串时,Python只会严格按照输入的内容拼接,不会自动在拼接的内容之间插入空格,你的代码里字符串末尾没有预留空格,所以变量和前后的字符串就直接连在一起了。

常见解决方法

  • 方法1:手动加空格拼接
    直接在需要分隔的位置补上空格字符即可,可以加在前后的字符串里,也可以单独拼接空格:
    # 字符串末尾加空格
    print("There once was a man named " + character_name + ",")
    # 单独拼接空格
    print("he was" + " " + character_age + " " + "years old")
    
  • 方法2:用print多参数特性(最省事)
    print函数传入多个参数时,默认会自动在参数之间加空格分隔,不需要手动拼接:
    print("There once was a man named", character_name, ",")
    print("he was", character_age, "years old")
    
  • 方法3:用f-string格式化(推荐,可读性最高)
    Python 3.6及以上版本支持f-string,直接在字符串模板里嵌入变量,空格直接写在模板对应位置即可:
    print(f"There once was a man named {character_name},")
    print(f"he was {character_age} years old")
    
  • 方法4:用str.format()格式化
    兼容性更好的写法,适合需要兼容低版本Python的场景:
    print("There once was a man named {},".format(character_name))
    print("he was {} years old".format(character_age))
    

内容的提问来源于stack exchange,提问作者Tariro Manyika

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.24 23:06:08