• 在字符串的开头或结尾处做文本匹配


    问题:

    我们需要在字符串的开头或结尾处按照指定的文本模式做检查,例如检查文件的扩展名、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
    不考虑业务场景,一味的争执技术的高下,都是耍流氓。
  • 相关阅读:
    PSP编程
    题库软件1.0发布
    ubuntu上安装netgear wg511v2驱动
    boost的编译
    Plot3D 0.3发布
    立体画板Plot3D
    求教团队内的朋友,在directx中,如何画虚线?
    OpenGL如何显示文本?
    JZ028数组中出现次数超过一半的数字
    JZ027字符串的排列
  • 原文地址:https://www.cnblogs.com/leoych/p/13344818.html
Copyright © 2020-2023  润新知