【问题标题】:What is wrong with this implementation of String interpolation in python*python *中字符串插值的这种实现有什么问题
【发布时间】:2011-08-17 05:05:35
【问题描述】:
import re

r = re.compile("#{([^}]*)}")

def I(string):
    def eval_str_match(m):
        return str(eval(m.group(1)))
    return r.sub(eval_str_match,string)

* 除了 python 品味/风格/标准

有没有比单字母方法更简洁的方法来调用它?
正则表达式有什么可能遗漏的吗?
我应该使用 repr 而不是 str 吗?
我知道 eval 可能很危险,但我不明白为什么

I("#{some_func()}\n")

然后更糟

"%s\n" % str(some_func())

【问题讨论】:

  • 更糟糕的是,您没有从语言或 IDE 进行任何错误检测。此外,如果您忘记了 # 用户将看到实际代码。此外,如果您不小心在包含用户输入的字符串上调用了“I”,您将面临很大的安全漏洞。可能还有更多原因。
  • 也许是一个 ide 或一个检查器,但我认为无论哪种方式,python 都会出现异常,不是吗?
  • 如果你有类似 "foo)(" 的语法错误,Python 会在模块加载时引发异常。

标签: python string-interpolation


【解决方案1】:

不确定您要完成什么,但这行得通吗?

I = '{}\n'.format
I(some_func())

def I(func):
    return "%x\n" % func()
I(some_func())

使用评论中的示例,

I([x*2 for x in [1,2,3]])

效果很好(虽然我不知道你希望输出是什么样的),就像

I(''.join((self.name, ' has ', self.number_of_children)))

但你真的应该只是在做

'{} has {}'.format(self.name, self.number_of_children)

仍然是一行。

【讨论】:

  • 我正在尝试做 ruby​​ 风格的字符串插值
  • 你甚至可以在没有多行的情况下做一些疯狂的事情,比如 I("#{[x*2 for x in [1,2,3]]}")。但主要用于 I(" (#{self.name}) has #{self.number_of_children}")
  • 将变量/表达式放入字符串的简单语法
  • 已编辑以显示该内容。我看不出 Python 的语法有多复杂。
  • 如果您想要更清晰,可以使用命名替换...'{name} has {num_children}'.format(name=self.name, num_children=self.num_children) 在我看来比 ruby​​ 版本更清晰。另外,如果您想保持简单,self.name + ' has ', str(self.num_children) 有什么问题?编辑:您刚刚评论说您更喜欢这个:)
【解决方案2】:

这是我想出来的。

在 my_print.py 中:

import sys

def mprint(string='', dictionary=None):
    if dictionary is None:            
        caller = sys._getframe(1)
        dictionary = caller.f_locals
    print string.format(**dictionary)

示例:

>>> from my_print import mprint
>>> name = 'Ismael'
>>> mprint('Hi! My name is {name}.')
Hi! My name is Ismael.
>>> new_dict = dict(country='Mars', name='Marvin',
...                 job='space monkey', likes='aliens')
>>> mprint("Hi! My name is {name} and I'm from {country}."
...     " Isn't {name} the best name?!\nDo you know any other {name}?", new_dict)
Hi! My name is Marvin and I'm from Mars. Isn't Marvin the best name?!
Do you know any other Marvin?

见:

Python string interpolation implementation

【讨论】:

    猜你喜欢
    • 2011-06-12
    • 2013-08-27
    • 2013-05-06
    • 1970-01-01
    • 1970-01-01
    • 2015-12-04
    • 1970-01-01
    相关资源
    最近更新 更多