gpt4 book ai didi

python - 在 Python find() 调用中使两个字符相等

转载 作者:太空宇宙 更新时间:2023-11-04 10:58:17 25 4
gpt4 key购买 nike

例如,我想使用 Python 在可能显示为 'tune-yards'(带有连字符)的文本 block 中搜索 'tune yards' ) 并且它可能会说 'tune yards' (没有)。我希望两者都被视为匹配项。我正在使用 find() 函数。有没有一种很好的 Pythonic 方法来将 - 和空格视为一个相同的东西,而不是仅仅堆叠 elif 语句?

像这样的事情:(我知道这行不通 :P)

treating '-' as ' ':
if blockOfText.find('tune yards') > -1:
do something

最佳答案

>>> re.search('tune[ -]yards', '58 tune yards of music')
<_sre.SRE_Match object at 0x1ad68b8>
>>> re.search('tune[ -]yards', '35 tune-yards of trombone')
<_sre.SRE_Match object at 0x1ad6988>

并且匹配对象始终为真(其他可能的返回值为None),因此可以通过if 测试结果。

关于python - 在 Python find() 调用中使两个字符相等,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7943458/

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