如何解释Python变量赋值中的字符串格式?

2024-09-21 01:20:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在分析文本以检查是否存在,例如:

u'Your new contact email thedude@gmail.com has been confirmed.'

…其中电子邮件地址两边的文本将是常量,而电子邮件地址将不是常量,但在解析之前将已知。在

假设句子包含在名为response的变量中,电子邮件地址包含在address中。我可以做:

^{pr2}$

这有点凌乱,如果句子的文本发生变化,完全不方便。是否可以在变量赋值中使用字符串格式

sentence = 'Your new contact email %s has been confirmed'

以某种方式在运行时将地址传递到变量中?在


Tags: 文本comnewyour电子邮件email地址contact
3条回答

你当然可以!试试这个。。。在

sentence = 'Your new contact email {} has been confirmed'.format(address)

还有另一个(相当老土的)选择。。。在

^{pr2}$

这个替代方法也有其局限性,比如需要使用tuple来传递多个参数。。。在

sentence = 'Hi, %s! Your new contact email %s has been confirmed' % ('KemyLand', address)

编辑:根据OP的评论,如果格式字符串恰好在address之前存在,他会问如何做到这一点。实际上,这很简单。我可以给你看最后三个例子吗?。。。在

# At this moment, `address` does not exist yet.

firstFormat = 'Your new contact email address {} has been confirmed'
secondFormat = 'Your new contact email address %s has been confirmed'
thirdFormat = 'Hi, %s! Your new contact email %s has been confirmed'

# Now, somehow, `address` does now exists.

firstSentence = firstFormat.format(address);
secondSentence = secondFormat % address
thirdSentence = thirdFormat % ('Pyderman', address)

我希望这对你有所启示!在

也许这是一种简单的方法,但是如果我没听错的话,你可以。。在

在开始时,声明字符串,但是地址将放在通常不会重复的内容中。。。比如| | | | |(5个管道字符)。在

然后当你有了地址并想把它放进去时:

myString.replace('|||||', address)

这将把你的地址放在你需要的地方:)

我的理解是你试图创建一个字符串,然后,添加一个片段。对不起,如果我误解了你:)

这就是我通常对我的SQL查询、输出行和其他内容所做的:

sentence = 'Blah blah {0} blah'
...
if sentence.format(adress) in response:
    foo()
    bar()

所以基本上你可以把所有与I/O相关的字符串定义在一个地方,而不是整个程序都是硬编码的。但在同一个地方,您可以随时编辑它们,但只能以有限的方式('foo'.format()在参数太少或太多时抛出异常)。在

相关问题 更多 >

    热门问题