[Python] 字符串常用操作方法 |
您所在的位置:网站首页 › 字符串常用的5个方法 › [Python] 字符串常用操作方法 |
所谓判断即是判断真假,返回的结果是布尔数据类型: 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 |
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |