我正在分析文本以检查是否存在,例如:
u'Your new contact email thedude@gmail.com has been confirmed.'
…其中电子邮件地址两边的文本将是常量,而电子邮件地址将不是常量,但在解析之前将已知。在
假设句子包含在名为response
的变量中,电子邮件地址包含在address
中。我可以做:
这有点凌乱,如果句子的文本发生变化,完全不方便。是否可以在变量赋值中使用字符串格式
sentence = 'Your new contact email %s has been confirmed'
以某种方式在运行时将地址传递到变量中?在
你当然可以!试试这个。。。在
还有另一个(相当老土的)选择。。。在
^{pr2}$这个替代方法也有其局限性,比如需要使用
tuple
来传递多个参数。。。在编辑:根据OP的评论,如果格式字符串恰好在
address
之前存在,他会问如何做到这一点。实际上,这很简单。我可以给你看最后三个例子吗?。。。在我希望这对你有所启示!在
也许这是一种简单的方法,但是如果我没听错的话,你可以。。在
在开始时,声明字符串,但是地址将放在通常不会重复的内容中。。。比如| | | | |(5个管道字符)。在
然后当你有了地址并想把它放进去时:
这将把你的地址放在你需要的地方:)
我的理解是你试图创建一个字符串,然后,添加一个片段。对不起,如果我误解了你:)
这就是我通常对我的SQL查询、输出行和其他内容所做的:
所以基本上你可以把所有与I/O相关的字符串定义在一个地方,而不是整个程序都是硬编码的。但在同一个地方,您可以随时编辑它们,但只能以有限的方式('foo'.format()在参数太少或太多时抛出异常)。在
相关问题 更多 >
编程相关推荐