首页 > 其他 > 详细

04 字符串的操作

时间:2020-04-28 16:45:16      阅读:66      评论:0      收藏:0      [点我收藏+]
字符串
str1 = python
字符串可以索引
print(str1[1])     #>>> y

for char in str1:
    print(char)    #>>> p    y    t    h    o    n

1.查找和替换
字符串.find(目标字符串)在字符串中查询目标字符串的索引位置
str2 = hello python
index = str2.find(py)    #>>>6
index = str2.find(pyq)   #>>>-1 如果找不到目标字符串,则返回-1
index = str2.find(o)     #>>>4  只返回第一个查找到的字符的索引位置

字符串.find(目标字符串,开始索引位置,结束索引位置)在指定的范围内查询目标字符串的位置
index = str2.find(n,5,11) #>>>-1   查询范围是[开始索引,结束索引) 不包含结束索引,
index = str2.find(n,5)  #>>>11   如果只设置开始索引,则查询到最后一个元素
print(index)

字符串.replace(原内容,新内容,替换次数)生成一个新的字符串,将原内容替换为新内容,也可以指定替换次数
str3 = str2.replace(python,c) #字符串本身不能够修改,修改其实是生成一个新的字符串
str3 = str2.replace(o,c,1)#指定替换次数,默认是全部替换
print(str3) #>>>hellc python

2.拆分和拼接
字符串.split(分隔符,拆分次数) 将字符串按照分隔符进行拆分,并将拆分的字符串放入列表返回
str4 = hello-python-c
char_list = str4.split(-)#>>>[‘hello‘, ‘python‘,‘c‘]
char_list = str4.split(-,1)#>>>[‘hello‘, ‘python-c‘] 可以指定拆分次数


字符串拼接  方式1:字符串+字符串
str5 = hello + prthon  #>>>helloprthon
方式2:
连接符.join(字符串列表) 将列表中没u个字符串使用连接符连接起来,返回链接后的新字符串
str5 = -.join([hello,python,c])  #>>>hello-python-c

3.切片
切片:用于取出序列中的一部分元素
格式:字符串[开始索引:结束索引] 获取范围[开始索引,结束索引) 不包含结束索引
str1 = hello python
print(str1[0]) #>>>h 去除第一个元素
print(str1[0:5])#>>>hello 第1到第5个
print(str1[7:])#>>>ython 从第8个取到最后
print(str1[:])#>>>hello python 取出全部
print(str1[-2:])#>>>on 从倒数第二个开始取

4.步长
步长格式:字符串[开始索引:结束索引:步长]
步长格式:当前索引+步长 = 下一个数据的索引
str3 = python
print(str3[::2])  #pto
步长可以是负数,表示倒序取值
print(str3[::-1]) #nohtyp


其他处理
1.无序集合
特点:无序+去重
set1 = {bj,sh,bj,hz}
print(set1) #{‘bj‘, ‘sh‘, ‘hz‘}

list1 = [bj,sh,bj,hz]
set2 = set(list1)#将列表转为无序集合,去重
print(set2) #>>>{‘hz‘, ‘bj‘, ‘sh‘}
list2 = list(set2) #将去重后的无序集合转为列表
print(list2) #>>>[‘hz‘, ‘bj‘, ‘sh‘]

2.公共语法
内置函数 len() max() min()
获取字符串的元素数量(长度)
str1 = hello
print(len(str1)) #>>>5

取出列表中最大&最小值
list1 = [10,20,30,40,5,1,36]
print(max(list1)) #>>>40  取最大值
print(min(list1)) #>>>1   取最小值

切片  列表/元组/字符串都可以使用
touple1 = (20,30,40,50)
print(touple1[::2]) #(20, 40)

运算符
集合+集合    列表/元组/字符串都可以使用
list2 = [10,20]+[30,40]
print(list2) #>>>[10, 20, 30, 40]

集合*整数   列表/元组/字符串都可以使用
list3 = [10,20]*3
print(list3) #>>>[10, 20, 10, 20, 10, 20]

in/not in  列表/元组/字符串/字典都可以使用
str3 = hello
if lo in str3:
    print(包含数据)
else:
    print(不包含数据)  #>>>包含数据

dict1 ={name:zs,age:20}
if age in dict1: #字典判断的是键,不能判断值
    print(包含该键)

> >= ==   字符串/列表/元组都可以使用
if (1,2,3) <(1,3,4): #安位比较,哪一个比较出大小就结束比较
    print(成立) #>>>成立
if (1,3,4) < (1,2,5):
    print(成立) #这个是不成立的,因为判断到第二位大于后面的

04 字符串的操作

原文:https://www.cnblogs.com/guozhihao/p/12795184.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!