字符串的内置方法

字符串类型内置方法

优先掌握(重要)

1.索引取值

 s = 'llj handsome'
 print(s[2])

2

2.切片

 s = 'llj handsome'
 print(s[4:0:1])  # 1表示从左到右
 print(s[-4::-1])  # -1表示从右到左 # 不推荐掌握
 print(s[4:0:-1])  # -1表示从右到左

3.for 循环

 s = 'llj handsome'
 for i in s:
     print(i)

4.去空白 strip()

 s = 'llj handsome'
 print(s1.strip())  # 去两端的空白
 s2 = '***!!!!!llj handsome----***'
 print(s2.strip('-*!'))  # 指定多个字符一起去掉,只要strip里面有的字符就全部干掉
 print(s2.strip('llj'))  # 指定多个字符一起去掉,只要strip里面有的字符就全部干掉
 # s2.strip('*-!') # 首先判断字符串s的两端字符,为*,再去strip里找有没有*,有就去掉,再去判断字符串s的两端字符,!-,再从strip里面找,有去掉,没有停止去掉

5.切割 split()

 s2 = '***!!!!!llj handsome----***'
 print(s2.split())  # 默认以空格切割字符串
 print(s2.split('!'))  # 以!切割,切割的字符不显示

['!!!!!llj', 'handsome----'] ['', '', '', '', '', 'llj handsome----']

6.in 或 not in

 s2 = '***!!!!!llj handsome----***'
 print('*' in s2)  # True 判断字符串里有没有该字符
 print('$' not in s2)  # True

7.长度len

 s2 = '***!!!!!llj handsome----***'
 print(len(s2))  # 求字符串的长度

需要掌握(次要)

1.lstrip()和 rstrip()

 s2 = '***!!!!!llj handsome----***'
 print(s2.lstrip('*')) #去除左端的字符
 print(s2.rstrip('*')) #去除右端的字符

!!!!!llj handsome----* *!!!!!llj handsome----

2.rsplit

print(s2.rsplit('*', 1)) #从右端开始切割

3.lower&upper

s3 = 'aaabbJ'
print(s3.lower()) #字母全部小写
print(s3.upper()) #字母全部大写

aaabbj AAABBJ

4.startswith&endswith

s3 = 'aaabbJ'
print(s3.startswith('b')) #False 是否已该字符开头
print(s3.endswith('J')) #True 该字符是否在结尾

5.join(用的比较多)一般和split联用

s = '辣条/薯片/汽水/泡面/火腿肠/枸杞/当归/鹿茸'
s1 = s.split('/')
print(' '.join(s1)) #拼接,注意:数字不可和字符串拼接

辣条 薯片 汽水 泡面 火腿肠 枸杞 当归 鹿茸

6. replace

s2 = 'llj handsome'
print(s2.replace('llj', 'gebilaowang')) #替换

gebilaowang handsome

7.isdigit(纯数字)/isalpha(纯字母)

s2 = '12312'
print(s2.isdigit())# 判断该字符是否都是纯数字

s3 = 'aaac1c'
print(s3.isalpha()) #判断该字符是否都是纯字母

了解(能看得懂就行)

1..find()、rfind()、index()、rindex()、count()

s2 = '**23423***llj234234 $$ hand223423some******'
print(s2.find('$'))  # 从左找,找到第一个停止,找不到返回-1
print(s2.rfind('$'))  # 从右找,找到就停止,找不到返回-1
print(s2.index('$'))  # 找不到报错
print(s2.rindex('$'))  # 找不到报错
print(s2.count('$')) #该字符出现的次数

2.center|ljust|rjust|zfill

s2 = 'nick handsome'
print(s2.center(50, '*'))  # 居中
print(s2.ljust(50, '*'))  # 居左
print(s2.rjust(50, '*'))  # 居右
print(s2.zfill(50))  # 填充0居右

3.expandtabs

s2 = 'a	a'
print(s2)
print(s2.expandtabs(8))  # 针对	而言

4.captalize|swapcase|title 只针对英文

s2 = 'harry Potter'
print(s2.capitalize())  # 首字母(一句话的开头)大写,其他全小写,用在段落开始
print(s2.swapcase())  # 大小写互换
print(s2.title())  # 所有单词首字母大写

5.is系列

大多都是用不上的

可变or不可变(重要)

  • 可变:值变id不变,不可哈希

  • 不可变:值变id也变,可哈希

字符串属于不可变数据类型

 

原文地址:https://www.cnblogs.com/lulingjie/p/11289803.html