Python中的startswith和endswith函数使用实例

这篇文章主要介绍了Python中的startswith和endswith函数使用实例,特别是endswith函数,有了它,判断文件的扩展名、文件的类型在容易不过了,需要的朋友可以参考下

在Python中有两个函数分别是startswith()函数与endswith()函数,功能都十分相似,startswith()函数判断文本是否以某个字符开始,endswith()函数判断文本是否以某个字符结束。

startswith()函数

此函数判断一个文本是否以某个或几个字符开始,结果以True或者False返回。

复制代码代码如下:

text='welcome to qttc blog'
print text.startswith('w')      # True
print text.startswith('wel')    # True
print text.startswith('c')      # False
print text.startswith('')       # True

endswith()函数

此函数判断一个文本是否以某个或几个字符结束,结果以True或者False返回。

复制代码代码如下:

text='welcome to qttc blog'
print text.endswith('g')        # True
print text.endswith('go')       # False
print text.endswith('og')       # True
print text.endswith('')         # True
print text.endswith('g ')       # False

判断文件是否为exe执行文件

我们可以利用endswith()函数判断文件名的是不是以.exe后缀结尾判断是否为可执行文件

复制代码代码如下:

# coding=utf8
 
fileName1='qttc.exe'
if(fileName1.endswith('.exe')):
    print '这是一个exe执行文件'   
else:
    print '这不是一个exe执行文件'
 
# 执行结果:这是一个exe执行文件

判断文件名后缀是否为图片

复制代码代码如下:

# coding=utf8
 
fileName1='pic.jpg'
if fileName1.endswith('.gif') or fileName1.endswith('.jpg') or fileName1.endswith('.png'):
    print '这是一张图片'
else:
    print '这不是一张图片'
     
# 执行结果:这是一张图片

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Python提供了很多字符串内置函数,这里列举几个比较常用的: 1. `len(str)`:返回字符串的长度。 ```python str = "hello, world!" print(len(str)) # 输出:13 ``` 2. `str.upper()`和`str.lower()`:将字符串分别转化为大写和小写形式。 ```python str = "Hello, WoRlD!" print(str.upper()) # 输出:HELLO, WORLD! print(str.lower()) # 输出:hello, world! ``` 3. `str.capitalize()`和`str.title()`:将字符串的首字母或每个单词的首字母转化为大写。 ```python str = "hello, world!" print(str.capitalize()) # 输出:Hello, world! print(str.title()) # 输出:Hello, World! ``` 4. `str.find(sub, start, end)`和`str.index(sub, start, end)`:返回子字符串在原字符串的位置,若没有则返回-1或抛出异常。 ```python str = "hello, world!" print(str.find('o')) # 输出:4 print(str.index('o')) # 输出:4 print(str.find('z')) # 输出:-1 # print(str.index('z')) # 抛出异常:ValueError: substring not found ``` 5. `str.count(sub, start, end)`:返回子字符串在原字符串出现的次数。 ```python str = "hello, world!" print(str.count('o')) # 输出:2 ``` 6. `str.replace(old, new, count)`:将字符串的所有旧子字符串替换为新子字符串,count为替换次数,可省略,表示替换所有。 ```python str = "hello, world!" print(str.replace('l', 'L')) # 输出:heLLo, worLd! ``` 除此之外,还有很多其他的字符串内置函数,比如`str.startswith(prefix, start, end)`、`str.endswith(suffix, start, end)`、`str.strip(chars)`、`str.join(iterable)`等等。这些函数都有其特定的功能和用法,可以根据实际情况进行选择和使用。 引用:Python字符串内置函数功能与用法总结。主要介绍了Python字符串内置函数功能与用法,结合实例形式总结分析了Python常见字符串操作函数的功能、分类、使用方法及相关操作注意事项,需要的朋友可以参考下[^1]。 引用:python string内置函数表格。string.replace(str1, str2, num=string.count(str1)) [^2]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值