字符串格式只能用于print()函数和Python中的语句吗?

时间:2014-12-09 06:31:54

标签: python string search formatting match

iterator, i is "Roster ID 2006 has been deleted"

  if re.match("Roster ID 2006 has been deleted",  i): //works

  if re.match("Roster ID %s has been deleted" % i,  i): //does not seem to work

我不能在除打印功能和打印语句之外的任何地方使用字符串格式吗?

2 个答案:

答案 0 :(得分:1)

是的,您可以在外部使用字符串格式化。你的例子不起作用因为我是你要找的字符串。应该是一年,例如2006年

i = "Roster ID 2006 has been deleted"
print(re.match("Roster ID 2006 has been deleted",  i))
print(re.match("Roster ID %d has been deleted" % 2006,  i))

在这两种情况下,我们都会得到以下结果:

<_sre.SRE_Match object; span=(0, 31), match='Roster ID 2006 has been deleted'>
<_sre.SRE_Match object; span=(0, 31), match='Roster ID 2006 has been deleted'>

但你这样做:

re.match("Roster ID %s has been deleted" % i,  i)

与:

相同
re.match("Roster ID Roster ID 2006 has been deleted has been deleted",  i)
# thus you are getting None as a result of the match.

答案 1 :(得分:0)

你可以;但是"Roster ID %s has been deleted" % i只会生成与另一行相同的内容 - 即"Roster ID 2006 has been deleted" - 如果i是字符串"2006"或转换为该字符串的内容。因为你的工作&#34;语句为if re.match("Roster ID 2006 has been deleted", i):i实际上是您希望包含"Roster ID 2006 has been deleted"的长字符串。请确保您的参数顺序正确:

>>> help(re.match)
Help on function match in module re:

match(pattern, string, flags=0)
    Try to apply the pattern at the start of the string, returning
    a match object, or None if no match was found.