在下面的python代码中
import re
myText = "The color of the car is red. Which is a popular color."
regularExp = "The color of the car is\s*(?P<color>\w*)..*"
pattern = re.compile(regularExp)
match = re.search(pattern, myText)
color = match.groups("color")
print(color)
我希望输出是red
。但我得到的是('red',)
。我做错什么了
re.search返回一个match object,正如您所看到的
groups
方法总是返回一个元组。因此,要么访问结果color[0]
的第一个元素,要么改用group
函数:另请注意,
match.groups("color")
可能并不像您认为的那样,引用文档:这意味着您将设置颜色为“颜色”如果没有找到匹配您的颜色组
对于match对象
m
,m.groups
返回一个tuple
,一个不可变的序列。你可以索引它或者或者
你说
('red',)
含有不需要的字符。这可能意味着您需要重新学习基本的python,因为您无法识别tuple
打印的是元组,而不是字符串。请尝试以下操作:
或(信用证:Wiktor Stribi)ż电子战):
相关问题 更多 >
编程相关推荐