• 请不要在回答技术问题时复制粘贴 AI 生成的内容
5TuNan
V2EX  ›  程序员

关于 Python f"" 和 format()

  •  
  •   5TuNan · Jun 9, 2020 · 3711 views
    This topic created in 2354 days ago, the information mentioned may be changed or developed.

    当下有这么一个场景:

    username = '川建国'
    print(f"名字:{username}, 我爱{我的国}")
    

    但是 Python 一直在报 "我的国"没有定义,并且"我的国"前后的{}还必须要带着。无奈只能使用 % 了。

    请教各位大佬有没有解决方法。

    11 replies  •  2020-06-09 20:52:28 +08:00
    Trim21
    Trim21
    Jun 9, 2020 via Android
    1
    f""+""
    weyou
    weyou
    Jun 9, 2020
    2
    print(f"名字:{username}, 我爱{{我的国}}")
    Drapor
    Drapor
    Jun 9, 2020
    3
    ```
    print(f"名字:{username}, 我爱{{我的国}}")
    ```
    kokutou
    kokutou
    Jun 9, 2020
    4
    特殊符号要转义。。
    swulling
    swulling
    Jun 9, 2020 via iPhone
    5
    两个大括号括起来就可以了
    yeyu123
    yeyu123
    Jun 9, 2020
    6
    f 里面 {}中是个变量. 第一个 username =川建国, 第二个 我的锅=?
    zdnyp
    zdnyp
    Jun 9, 2020
    7
    我的国确实没定义啊。

    username = '川建国'

    myworld = '中国'

    print(f"名字:{username}, 我爱{myworld}") 或者 print(f"名字:{username}, 我爱{'我的国'}")
    5TuNan
    5TuNan
    OP
    Jun 9, 2020
    8
    @zdnyp 我的国 是个普通字符串。前后的{}也要保留,不做变量使用。
    5TuNan
    5TuNan
    OP
    Jun 9, 2020
    9
    @weyou @swulling @Drapor 感谢三位大佬。

    @kokutou 感谢,我现在就是为了寻找转义方法

    @Trim21 的确是,哈哈。
    no1xsyzy
    no1xsyzy
    Jun 9, 2020
    10
    https://www.v2ex.com/t/671782#r_8971898
    …… 你可以续行混合 f-string 和一般的 string

    username = '川建国'
    print(f"名字:{username}, " "我爱{我的国}")
    qW7bo2FbzbC0
    qW7bo2FbzbC0
    Jun 9, 2020
    11
    ```
    print(f"名字:{username}, 我爱{{我的国}}")
    ```
    c# 也是如此
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   2319 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 109ms · UTC 13:25 · PVG 21:25 · LAX 05:25 · JFK 08:25
    ♥ Do have faith in what you're doing.