如何在Python变量赋值中考虑字符串格式?

时间:2015-10-13 05:35:38

标签: python string variables string-formatting

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

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

...电子邮件地址任意一侧的文本将保持不变,电子邮件地址不会保持不变,但在解析之前就会知道。

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

'Your new contact email' + address + 'has been confirmed' in response

如果句子的文字发生变化,这有点不整洁,而且非常不方便。是否有可能在变量赋值中利用字符串格式,例如

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

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

3 个答案:

答案 0 :(得分:2)

当然可以!试试这个......

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

还有其他(相当hacky)替代......

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

这个替代方案也有其局限性,例如要求使用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)

我希望这能为你带来一些启示!

答案 1 :(得分:1)

也许是一种黑客的做法,但如果我理解正确的话,这就是你的方式......

一开始,声明字符串,但是地址会去哪里,放入一些永远不会重复的东西......就像||||| (5个管道字符)。

然后当你有地址并希望在do:

中弹出它
export GOROOT=/usr/local/opt/go/libexec # install via brew

这会将您的地址放在您需要的地方:)

我的理解是你正在尝试创建一个字符串,然后再添加一个。抱歉,如果我误解了你:)

答案 2 :(得分:1)

这是我通常用我的SQL查询,输出行等做的事情:

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

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