V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
• 请不要在回答技术问题时复制粘贴 AI 生成的内容
5TuNan
V2EX  ›  程序员

关于 Python f"" 和 format()

  •  
  •   5TuNan · Jun 9, 2020 · 3198 views
    This topic created in 2153 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
        1
    Trim21  
       Jun 9, 2020 via Android
    f""+""
    weyou
        2
    weyou  
       Jun 9, 2020
    print(f"名字:{username}, 我爱{{我的国}}")
    Drapor
        3
    Drapor  
       Jun 9, 2020
    ```
    print(f"名字:{username}, 我爱{{我的国}}")
    ```
    kokutou
        4
    kokutou  
       Jun 9, 2020
    特殊符号要转义。。
    swulling
        5
    swulling  
       Jun 9, 2020 via iPhone
    两个大括号括起来就可以了
    yeyu123
        6
    yeyu123  
       Jun 9, 2020
    f 里面 {}中是个变量. 第一个 username =川建国, 第二个 我的锅=?
    zdnyp
        7
    zdnyp  
       Jun 9, 2020
    我的国确实没定义啊。

    username = '川建国'

    myworld = '中国'

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

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

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

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