Python-判断字符串是否以某个字符串开头或结尾?
2024-09-02 13:43:40
案例:
某文件系统目录下有一系列文件:
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()
最新文章
- javascript的正则表达式学习
- torrent
- WEKA运行LIBSVM出现problem evaluating classifier:rand
- 让U盘永不中毒的解决办法
- MySQL模拟:线上误update的恢复
- Reference in the manifest does not match the identity of the downloaded assembly
- 学习C++ Primer 的个人理解(七)
- 《疯狂java讲义》笔记 1-5章
- 鼠标移入 移出div div会消失的处理
- CSS盒模型和margin重叠
- java中数组复制的两种方式
- linux C中调用shell命令和运行shell脚本
- Git使用基础介绍
- Rabbitmq 安装后采坑
- Mergeable Stack(链表实现栈)
- javaweb中的乱码问题
- 一个JS Class的“增删改查”
- 微信小程序新版用户授权方式处理
- HashMap实现原理(转)
- 2017年10月21日 数据库基础&;三大范式