python 基础数据结构之字符串操作

#切割部分
s = 'I love you more than i can say' # 切割字符串 # sep:指定按照什么进行切割,默认按照空格切割 # maxsplit:指定最大切割次数,默认不限制次数 # ret = s.split(sep='abc', maxsplit=1) # 从右边进行切割 ret = s.rsplit(' ', maxsplit=7)#以空格切割 print(ret) #等价于下面操作 s = 'I love you more than i can say' ret = s.split() print(ret)
s = 'Hello\nworld'
# 按照换行进行切割

print(s.splitlines())
s = 'I love you more than i can say'
ret = s.split()
print(ret)
#字符串拼接
s2 = '*'.join(ret)
print(s2)#I*love*you*more*than*i*can*say
#查询操作
s = 'Hi buddy, if you have something to say, than say; if you have nothing to say, than go.' # 子串查找:找到首次出现的位置,返回下标,找不到返回-1 ret = s.find('hello') print(ret)#-1 # 从后面查找 ret = s.rfind('to')#70 print(ret) print(s[70],s[71])#t o # 统计子串出现的次数 ret = s.count('if') print(ret)#2
#判断部分
# 判断是否已指定内容开头
s = 'Hi buddy, if you have something to say, than say; if you have nothing to say, than go.'
ret = s.startswith('Hi')
print(ret)#True
# 判断是否已指定内容结尾
ret = s.endswith('go.')
print(ret)#True

s = 'hellO worlD!'
# 转换为全大写
print(s.upper())#HELLO WORLD!
# 转换为全小写
print(s.lower())#hello world!
# 大小写转换
print(s.swapcase())#HELLo WORLd!
# 首字母大写
print(s.capitalize())#Hello world!
# 每个单词首字母大写
print(s.title())#Hello World!
# 用指定的内容替换指定内容,还可以值替换次数
print(s.replace('l', 'L', 2))#heLLO worlD!

s = 'abcABC2'
# 是否是全大写
print(s.isupper())#False
# 是否是全小写
print(s.islower())#False
# 是否每个单词首字母都大写
print(s.istitle())#False
# 是否是全数字字符
print(s.isdecimal())#False
# 是否是全字母
print(s.isalpha())#False
# 是否全是字母或数字
print(s.isalnum())#False

猜你喜欢

转载自www.cnblogs.com/liangliangzz/p/10148903.html