二、字符串,元祖,列表等数据操作

一、字符串操作


#replace将字符串中某个子字符串替换成另外一个字符串,但不改变原有的值
a='helloword'
b=a.replace('h','H')
print(b) #Helloword

#index返回字符串中子字符串的位置
indx=a.index('o')
print(indx) #4

#isspace判断字符串是否是纯空格
a=' '
print(a.isspace()) #True

#isdecimal判断字符串是否是纯数字组成
b='12231231'
print(b.isdecimal()) #True

#istitle判断字符串首字母是否大写
c='Hello'
print(c.istitle()) #返回True

#1、isupper判断字符串所有字母是否大写 2、upper将字符串全部改为大写,注意是不改变原来的字符串的
d='hello'
print(d.isupper()) #返回False
new=d.upper()
print(new) #HELLO

#1、islower判断字符串所有字母是否小写 2、lower将字符串全部改为小写,注意是不改变原来的字符串的
e='HELLO'
print(e.islower()) #返回False
new=e.lower()
print(new) #hello


#字符串也可以循环遍历,因为它也是一个可迭代对象


"""字符串切片"""

a="abcdefghijklmn"
#从第一个切到第五个
qp=a[2:5]
print(qp) #cde

#每隔俩个取一个
qp=a[::2]
print(qp) #acegikm

#倒序字符
print(a[::-1]) #nmlkjihgfedcba

#从右边切片,取到def,并将其倒序
print(a[-9:-12:-1]) #fed
print(a[-9:2:-1]) #fed
 

二、列表操作

 1 #append向列表添加元素
 2 a=[]
 3 a.append('张三')
 4 print(a)
 5 
 6 #pop删除列表中元素,默认删除最后一个,若pop后面带数字则删除指定位置的元素;pop方法删除的同时并返回删除的元素
 7 a=['a','b','c','d']
 8 element=a.pop()  #删除了d元素
 9 print(a)
10 print(element)
11 element2=a.pop(0)
12 print(a)
13 
14 #remove也是删除某个元素,只不过里面跟的参数是要删除的元素对象
15 a=['a1','a2','a3']
16 a.remove('a2')
17 print(a)
18 
19 
20 #clear是清空列表
21 a=['b1','b2','b3','b4']
22 a.clear()
23 print(a)
24 
25 
26 #关键字del是删除列表,也可删除指定元素
27 a=['c1','c2','c3']
28 del a[1]  #删除指定元素
29 del a  #删除列表
30 print(a)

 三、完整的for循环(和else一起使用)

#完整的for循环
"""
for .... in ...:
else:
 要执行的语句
"""
a=['张三','李四','王五']
b='李四'
for i in a:
    if i==b:
        print('找到了%s'%(b))
        break  #若果for循环没有遍历完,被打断,就不会执行else语句
               #当for循环全部遍历完后才会执行else语句
else:
    print('未找到%s'%b)
原文地址:https://www.cnblogs.com/lz-tester/p/9121887.html