• Python-判断字符串是否以某个字符串开头或结尾?


    案例:

           某文件系统目录下有一系列文件:

        1.c

        2.py

        3.java

        4.sh

        5.cpp

        ......

      编写一个程序,给其中所有的.sh文件和.py文件加上可执行权限

    如何解决这个问题?

      1. 先获取目录下文件

      2. 通过startswith() 和endswith()方法判断是否以某个字符开头或结尾,列表解析留下满足条件的文件名

      3. 迭代列表,给对应的文件赋予权限

    #!/usr/bin/python3
    
    __author__ = 'beimenchuixue'
    __blog__ = 'http://www.cnblogs.com/2bjiujiu/'
    
    import os
    import stat
    
    
    def chmod_py(target_path):
        # 获得当前文件下目录文件
        file_l = os.linesdir(target_path)
        
        # startswith中拥有多个参数必须是元组形式,只需满足一个条件,返回True
        target_file = [name for name in file_l if name.startswith(('.sh', '.py'))]
        
        for file in target_file:
            # 给满足条件的文件所有者赋予执行权限
            os.chmod(file, os.stat(file).st_mod | stat.S_IXUSR)
    
    
    if __name__ == '__main__':
        # 目标目录
        target_path = '.'
        
        chmod_py(target_path=target_path)
    

      

      判断字符是否以某个字符开头和结尾

    # -*- coding: utf-8 -*-
    # !/usr/bin/python3
    
    __author__ = 'beimenchuixue'
    __blog__ = 'http://www.cnblogs.com/2bjiujiu/'
    
    
    def check_str(value):
        # 检查你输入的是否是字符类型
        if isinstance(value, str):
            # 判断字符串以什么结尾
            if value.endswith('.sh'):
                return '%s 是以.sh结尾的字符串' % value
            # 判断字符串以什么开头
            elif value.startswith('xi'):
                return '%s 是以xi开头的字符串' % value
            else:
                return '%s 不满足以上条件的字符串' % value
        else:
            return '%s is not str' % value
        
    
    def main():
        str_one = 'bei_men.sh'
        resp_one = check_str(str_one)
        print(resp_one)
        
        str_two = 'xi_du.py'
        resp_two = check_str(str_two)
        print(resp_two)
        
        str_three = 233
        resp_three = check_str(str_three)
        print(resp_three)
    
    
    if __name__ == '__main__':
        main()
    

      

      

     

      

      

  • 相关阅读:
    2017-2018-1 20145237、20155205、20155218实验一 开发环境的熟悉
    作业三总结
    作业二总结
    作业总结1
    自我介绍
    计科16-4刘悦
    第九次作业
    作业八
    作业七
    作业六
  • 原文地址:https://www.cnblogs.com/2bjiujiu/p/7255599.html
Copyright © 2020-2023  润新知