是否有更有效的方式加入元组?既然我的rx给了我一个元组? 此外,c是' 7:30' ' AM'最后,我需要' 30 AM'
import re
rx = r"(?i)\b(\d{1,2}:\d{2})(?:-\d{1,2}:\d{2})?(\s*[pa]m)\b"
s = "ankkjdf 7:30-8:30 AM dds "
matches = re.findall(rx, s)
m=str(matches)
a =''.join(m[2:8])
b= ''.join(m[9:15])
c = "".join(a + b)
print(c)
答案 0 :(得分:2)
>>> import re
>>> rx = r"(?i)\b(\d{1,2}:\d{2})(?:-\d{1,2}:\d{2})?(\s*[pa]m)\b"
>>> s = "ankkjdf 7:30-8:30 AM dds "
>>> matches = re.findall(rx, s)
>>> matches
[('7:30', ' AM')]
>>> [ "".join(x) for x in matches]
['7:30 AM']
>>>
或
>>> "".join(matches[0])
'7:30 AM'
>>>
或直接来自
>>> [ "".join(x) for x in re.findall(rx, s)]
['7:30 AM']
>>> "".join( re.findall(rx, s)[0] )
'7:30 AM'
>>>
没有理由做m=str(matches)
,只是把你得到的东西融合在一起......
使用最新的例子
>>> test="Join us for a guided tour of the Campus given by Admissions staff. The tour will take place from 1:15-2:00 PM EST and leaves from the Admissions Office."
>>> [ "".join(x) for x in re.findall(rx, test)]
['1:15 PM']
>>> "".join( re.findall(rx, test)[0] )
'1:15 PM'
>>>