[Python字符串] 6个常用判断操作方法

所谓判断即是判断真假,返回的结果是布尔数据类型: True 或 False

以下是字符串常用操作方法中的6个判断方法,每个方法都有语法且利用案例来说明怎么使用,方法使用很简单,大家快速掌握就好。虽说字符串的一些操作方法很简单,可能会有刚接触编程的小白不是特别理解,我们有配套的python视频教程,不大懂得宝宝可以去看看视频或许就明白了。

1、startswith()

检查字符串是否是以指定子串开头,是则返回True,否则返回False。如果设置开始和结束位置下标,则在指定范围内检查。

语法:

字符串序列.startswith(子串,开始位置下标,结束位置下标)

快速体验:

myStr = 'hello world and Python and java and php'
print(myStr.startswith('hello'))  # True
print(myStr.startswith('hel'))    # True
print(myStr.startswith('helt'))   # False

2、endswith()

检查字符串是否是以指定子串结尾,是则返回True,否则返回False。如果设置开始和结束位置下标,则在指定范围内检查。

语法:

字符串序列.endswith(子串,开始位置下标,结束位置下标)

快速体验:

myStr = 'hello world and Python and java and php'
print(myStr.endswith('php'))  # True
print(myStr.endswith('hp'))    # True
print(myStr.endswith('ppp'))   # False
print(myStr.endswith('ph'))   # False

3、isalpha()

如果字符串至少有一个字符并且所有字符都是字母则返回True,否则返回False。

语法:

字符串序列.isalpha()

快速体验:

myStr1 = 'python'
myStr2 = 'python123456'
print(myStr1.isalpha())  # True
print(myStr2.isalpha())  # False

4、isdigit()

如果字符串只包含数字则返回True,否则返回False。

语法:

字符串序列.isdigit()

快速体验:

myStr1 = 'python123'
myStr2 = '123456'
print(myStr1.isdigit())  # False
print(myStr2.isdigit())  # True

5、isalnum()

如果字符串至少有一个字符并且所有字符都是字母或数字则返回True,否则返回False。

语法:

字符串序列.isdigit()

快速体验:

myStr1 = 'python123'
myStr2 = '123456--、、'
print(myStr1.isalnum())  # True
print(myStr2.isalnum())  # False

6、isspace()

如果字符串中只包含空白,则返回True,否则返回False。

语法:

字符串序列.isspace()

快速体验:

myStr1 = 'p y t h o n 1 2 3'
myStr2 = '   '
print(myStr1.isspace())  # False
print(myStr2.isspace())  # True

好文推荐

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值