【问题标题】:Transform string to f-string将字符串转换为 f 字符串
【发布时间】:2017-11-29 03:30:40
【问题描述】:

如何将经典字符串转换为 f 字符串?

variable = 42
user_input = "The answer is {variable}"
print(user_input)

输出:The answer is {variable}

f_user_input = # Here the operation to go from a string to an f-string
print(f_user_input)

所需输出:The answer is 42

【问题讨论】:

    标签: python python-3.x string-interpolation f-string


    【解决方案1】:

    f 字符串是语法,而不是对象类型。您不能将任意字符串转换为该语法,该语法会创建一个字符串对象,而不是相反。

    我假设您想使用user_input 作为模板,所以只需在user_input 对象上使用str.format() method

    variable = 42
    user_input = "The answer is {variable}"
    formatted = user_input.format(variable=variable)
    

    如果您想提供可配置的模板服务,请创建一个包含所有可插值字段的命名空间字典,并使用 str.format()**kwargs 调用语法来应用命名空间:

    namespace = {'foo': 42, 'bar': 'spam, spam, spam, ham and eggs'}
    formatted = user_input.format(**namespace)
    

    然后,用户可以在{...} 字段中使用命名空间中的任何键(或不使用,忽略未使用的字段)。

    【讨论】:

    • 好的,我明白了。但这意味着我必须知道用户可以输入的所有值,但情况并非如此:输入将是一个 SQL 查询,我真的不知道用户将输入什么:select * from {table} where day = {day} and client = {client}。在这种情况下我可以如何做到这一点有什么想法吗?
    • @fmalaussena:那么任意条目会给你什么值?您可以预先解析格式并查看使用了哪些字段名称,请参阅Dynamic fields in a Python stringHow to get the variable names from the string for the format() method
    【解决方案2】:

    真正的答案可能是:不要这样做。通过将用户输入视为 f 字符串,您将其视为产生安全风险的代码。您必须真正确定您可以信任输入的来源。

    如果您知道用户输入可以信任,您可以使用eval()

    variable = 42
    user_input="The answer is {variable}"
    eval("f'{}'".format(user_input))
    'The answer is 42'
    

    编辑添加:@wjandrea 指出 another answer 对此进行了扩展。

    【讨论】:

    【解决方案3】:
    variable = 42
    user_input = "The answer is {variable}"
    # in order to get The answer is 42, we can follow this method
    print (user_input.format(variable=variable))
    

    (或)

    user_input_formatted = user_input.format(variable=variable)
    print (user_input_formatted)
    

    好链接https://cito.github.io/blog/f-strings/

    【讨论】:

      【解决方案4】:

      只是添加一种类似的方法来做同样的事情。 但是 str.format() 选项更可取使用。

      variable = 42
      user_input = "The answer is {variable}"
      print(eval(f"f'{user_input}'"))
      

      【讨论】:

        【解决方案5】:

        您可以使用 f-string 代替普通字符串。

        variable = 42
        user_input = f"The answer is {variable}"
        print(user_input) 
        

        【讨论】:

          猜你喜欢
          • 2018-04-30
          • 2019-10-10
          • 2019-01-05
          • 1970-01-01
          • 2020-01-19
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-08-22
          相关资源
          最近更新 更多