Python基础知识(字符串的常用 *** 作

Python基础知识(字符串的常用 *** 作,第1张

78.字符串的常用 *** 作_字符串的劈分

字符串的劈分功能:

split():从字符串的左边开始劈分,默认的劈分字符串是空格字符串,返回的值都是一个列表

以通过参数sep指定劈分字符串是劈分符

通过参数maxsplit指定劈分字符串时的最大劈分次数,在经过最大次劈分之后,剩余的子串会单独作为一部分

rsplit():从字符串的右边开始劈分,默认的劈分字符串是空格字符串,返回的值是一个列表

以通过参数sep指定劈分字符串劈分符

通过参数maxsplit指定劈分字符串时的最大劈分次数,在经过最大次劈分之后,剩余的子串会单独作为一部分

 

s='hello world Python'
lst=s.split()
print(lst)
s1='hello|world|Python'
print(s1.split(sep='|'))
print(s1.split(sep='|',maxsplit=1))
print('-------------')
'''rsplist()从右侧开始劈分'''
print(s.rsplit())
print(s1.rsplit('|'))
print(s1.rsplit(sep='|',maxsplit=1)) #指定了第一部分劈分


#结果
['hello', 'world', 'Python']
['hello', 'world', 'Python']
['hello', 'world|Python']
-------------
['hello', 'world', 'Python']
['hello', 'world', 'Python']
['hello|world', 'Python']

 

79.字符串的常用 *** 作_字符串判断的相关方法

判断字符串的方法功能:

isidentifier():判断指定的字符串是不是合法的标识符

isspace():判断指定的字符串是否全部由空白字符组成(回车、换行、水平制表符)

isalpha():判断指定的字符串是否全部由字母组成

isdeximal():判断指定字符串是否全部由十进制的数字组成

isnumeric():判断指定的字符串是否全部由数字组成

isalnum():判断指定字符串是否全部由字母和数字组成

s='hello,python'
print('1.',s.isidentifier())
print('2.','hello'.isidentifier())
print('3.''张三'.isidentifier())
print('4.''张三_123'.isidentifier())

print('5.','\t'.isspace())
print('6.','abc'.isalpha())
print('7.','张三'.isalpha())
print('8.','张三1'.isalpha())

print('9.','123'.isalpha())
print('10.','123四'.isdecimal())

#结果
1. False
2. True
False
False
5. True
6. True
7. True
8. False
9. False
10. False

 

80.字符串的常用 *** 作_替换与合并

字符串 *** 作的其它方法:

字符串替换:replace() 第一个参数指定被替换的子串,第二个参数指定替换子串的字符串,该方法返回替换后得到的字符串,替换前的字符串不发生变化,调用该方法时可以提供第三个参数指定最大的替换次数

join():将列表或元组中的字符串合并成一个字符串

 

s='hello,Python'
print(s.replace('Python','Java'))
s1='hello,Python,Python,Python'
print(s1.replace('Python','Java',2))
'''列表'''
lst=['hello','java','Python']
lst=['hello','java','Python']
print('|'.join(lst))
print(''.join(lst))
'''元组'''
t=('hello','Java','Python')
print(''.join(t))
'''字符串'''
print('*'.join('Python'))

#结果
hello,Java
hello,Java,Java,Python
hello|java|Python
hellojavaPython

 

81.字符串的比较 *** 作 字符串的比较 *** 作

运算符:>,>=,<,<=,==,!=

比较规则:首先比较两个字符串中的第一个字符,如果相等则继续比较下一个字符,依次比较下去,直到两个字符串中的字符不相等时,其比较结果就是两个字符串的比较结果,两个字符串中的所有后续字符将不再被比较

比较原理:两上字符进行比较时,比较的是其ordinal value(原始值),调用内置函数ord可以得到指定字符的ordinal value。与内置函数ord对应的是内置函数chr,调用内置函数chr时指定ordinal value可以得到其对应的字符

 

'''== 与is的区别 == 比较的是value is 比较的是id是否相等'
'''
a=b='Python'
c='Python'
print(a==b)     #True
print(b==c)     #True

print(a is b)   #True
print(a is c)   #True
print(id(a))    #1481580692656
print(id(b))    #1481580692656
print(id(c))    #1481580692656

#结果
True
False
97 98
20940
a b
凌
True
True
True
True
1481580692656
1481580692656
1481580692656

进程已结束,退出代码0

 

 

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/737342.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-04-28
下一篇 2022-04-28

发表评论

登录后才能评论

评论列表(0条)

保存