gpt4 book ai didi

python - 加入元组的更有效方法?

转载 作者:太空宇宙 更新时间:2023-11-04 03:00:51 24 4
gpt4 key购买 nike

有没有更有效的连接元组的方法?因为我的 rx 给了我一个元组?而且c最后是'7:30''AM',我需要'7: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)

最佳答案

>>> 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'
>>>

关于python - 加入元组的更有效方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40953247/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com