Python3 中 字符串操作示例

Python3 中 字符串操作示例

# -*- coding:utf-8 -*-
str = 'abcdededededefg'

#根据索引获取数据,0查看第一个字符,-1 查看从右开始的第一个字符
print(str[0])
print(str[-1])

#字符串截取/切片
print(str[2:]) # cdededededefg ,从索引为2的字符开始截取一直到最后
print(str[1:3]) # bc ,从索引为1的字符开始截取到3-1位置,不包含3所在位置字符
print(str[:3]) # abc ,从头开始截取到3-1位置,不包含3所在位置字符
print(str[0:6:2]) # ace ,从索引为0的字符开始截取到6-1位置,不包含6所在位置字符,切片步长为2,每两个字符截取一个
print(str[::-1]) # gfedededededcba,字符串倒叙输出

#使用index获取字符所在索引
print(str.index('c'))

#查找S.find(sub[, start[, end]]) -> int 可以搜索字符串,根据start ----end 切片范围内搜索
print(str.find('f'))
print(str.find('de',6,9))

# strip 可删除字符串开头和结尾的空格,中间内容不会删除
f = ' jj ll '
print(f.strip())

#获取字符串的长度
print(len(str))

#替换S.replace(old, new[, count]) -> str old=被修改的字符、字符串 new=修改的字符、字符串, count=被替换的次数
print(str.replace('d','D')) #返回:'abcDeDeDeDeDefg'
print(str.replace('d','D',2)) #返回: 'abcDeDedededefg' 设置了count参数 只修改了两个

# S.center(width[, fillchar]) 以字符串为中心,左右补充字符 ,width = 设置的宽度,fillchar=补位字符
print(str.center(20,'-')) #返回:"--abcdededededefg---"

#isnumeric 字符串中如果为纯数字 返回True
s = '123'
print(s.isnumeric) #true
print(str.isnumeric()) #Flase

# S.split(sep=None, maxsplit=-1) -> list of strings
a = 'abcebcegbs'
b = a.split('b')
print(b) # 返回列表:['a', 'ce', 'ceg', 's'] ,以字符‘b’为分割符号,生成列表

#S.join(iterable)- > str返回一个字符串,它是字符串的串接iterable。元素之间的分隔符是s。
print('b'.join(b)) #返回一个字符串 abcebcegbs

#S.capitalize()- > str 返回一个大写的S,也就是第一个字符,有大写字母和其他小写字母。
print(str.capitalize()) #返回:Abcdededededefg

猜你喜欢

转载自www.cnblogs.com/TheEast/p/8948207.html