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

案例:

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

    1.c

    2.py

    3.java

    4.sh

    5.cpp

    ......

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

如何解决这个问题?

  1. 先获取目录下文件

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

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#!/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)

 

  

 

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# -*- 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()

 

  

 

 

  

 

 

  

 

  

 

posted @   梦_鱼  阅读(67856)  评论(0编辑  收藏  举报
编辑推荐:
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)
点击右上角即可分享
微信分享提示