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

如何在第12-14行用无空格f-string实现带空格的输出?

解决思路&代码示例

要做到f-string内部不写空格但输出带空格,其实不用纠结,用表达式生成空格就行,给你三个可行的写法:

  • 用ASCII码生成空格
    空格的ASCII编码是32,用chr(32)代替手动空格,代码如下:

    # 第12行
    print(f"{first}{chr(32)}{last}")
    # 第13行
    print(f"{street}{chr(32)}{city}")
    # 第14行
    print(f"{state}{chr(32)}{zipcode}")
    

    这样f-string里没有直接写空格字符,输出却会正常显示空格。

  • 提前定义空格变量
    先存一个空格变量,后续直接引用,可读性更好:

    sp = ' '
    # 第12行
    print(f"{first}{sp}{last}")
    # 第13行
    print(f"{street}{sp}{city}")
    # 第14行
    print(f"{state}{sp}{zipcode}")
    

    同样满足f-string内部无手动空格的要求,输出带空格。

  • 用join方法拼接
    如果是两个字符串要加空格分隔,str.join()会自动帮你加空格,写法更简洁:

    # 第12行
    print(f"{' '.join([first, last])}")
    # 第13行
    print(f"{' '.join([street, city])}")
    # 第14行
    print(f"{' '.join([state, zipcode])}")
    

    这里' '.join()的空格是join方法的参数,不算直接写在f-string的占位符之间,符合你的要求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 01:35:24