zoukankan      html  css  js  c++  java
  • 在字符串的开头或结尾处做文本匹配

    问题:

    我们需要在字符串的开头或结尾处按照指定的文本模式做检查,例如检查文件的扩展名、URL协议类型等。

    解决方案:

    有一种简单的方法可用来检查字符串的开头或结尾,只要使用str.startswith()和str.endswith()方法就可以了

     1 filename = 'spam.txt'
     2 result = filename.endswith('.txt')
     3 print(result)
     4 
     5 result1 = filename.startswith('file:')
     6 print(result1)
     7 
     8 url = "http://www.python.org"
     9 result2 = url.startswith('http:')
    10 print(result2)

    运行结果:

    True
    False
    True

    如果需要同时针对多个选项做检查,只需给startswith()和endswith()提供包含可能选项的元组即可:

    import os
    
    filenames = os.listdir('.')
    
    print(filenames)
    
    result = [name for name in filenames if name.endswith(('.py','.txt'))]
    print(result)
    
    result1 = any(name.endswith('.py') for name in filenames)
    print(result1)

    结果:

    ['2_2_1.py', '11.txt', '2_1.py', '2_2.py']
    ['2_2_1.py', '11.txt', '2_1.py', '2_2.py']
    True
    不考虑业务场景,一味的争执技术的高下,都是耍流氓。
  • 相关阅读:
    HDU 1058 Humble Numbers
    HDU 1421 搬寝室
    HDU 1176 免费馅饼
    七种排序算法的实现和总结
    算法纲要
    UVa401 回文词
    UVa 10361 Automatic Poetry
    UVa 537 Artificial Intelligence?
    UVa 409 Excuses, Excuses!
    UVa 10878 Decode the tape
  • 原文地址:https://www.cnblogs.com/leoych/p/13344818.html
Copyright © 2011-2022 走看看