Python基础:字符串操做

#字符串类型的生成
name = '小明' nums = str(9) print(name,'******',nums) #字符串的基本操做
 words = 'diFfrEnCe'
#根据索引获取值
print(words[1]) #切片
print(words[1:4]) #带步进值的切片
print(words[0:4:2]) #遍历字符串 # for item in words: # print(item)

#swapcase 大小写互转
print(words.swapcase()) #upper 全大写
print(words.upper()) #lower 全小写
print(words.lower()) #capitalize 第一个字母大写
print(words.capitalize()) #title 单词首字母大写
print('hello world'.title()) #find 查找值定字符第一次出现的位置,找到返回索引,找不到返回-1(顺序查找.可指定范围) #res = words.find('e')
res = words.find('g') print(res) #rfind 查找值定字符第一次出现的位置,找到返回索引,找不到返回-1(逆序查找,可指定范围)
res = words.rfind('e') print(res) #len 获取字符串长度
print(len(words)) #count 指定字符出现的次数(可给范围)
res = words.lower().count('f',3,8) print(res) #index与find相似,找不到返回ValueError: substring not found # res = words.index('g') # print(res)

#startwith 检测字符串是否以值定字符开头,返回布尔值
res = words.startswith('diff') print(res) #endwith 检测字符串是否以指定字符结束
res = words.endswith('hh') print(res) #isupper 检测字符串是否有大写字母组成
res = words.isupper() print(res) res = words.upper().isupper() print(res) #islower 检测字符串是否有小写字母组成

#istitle 检测字符串是否符合首字母大写

#isalnum 检测字符串由数字、字母(汉字及其余文字)组成

#isalpha 检测字符串是否由字母和文字组成

#isnumeric 检测字符串是否由数字组成

#isdecimal 检测字符串是否由数字组成

#isspace 检测字符串是否由空白字符组成

#split 使用指定字符切割字符串,返回列表
words = 'life is short , you need python' res = words.split(' ') print(res) #splitlines 使用换行符切割字符串
res = words.splitlines() print(res) #join() 将容器数据使用值定字符链接成一个字符串
words = ['life', 'is', 'short', ',', 'you', 'need', 'python'] res = '\r\n'.join(words) print(res) #zfill 零填充
words = '1234567' res = words.zfill(9) print(res) #center 使用指定字符填充字符串,原有内容居中显示
words = 'python' res = words.center(10,'*') print(res) #ljust 使用指定字符填充字符串,原有内容居左显示
words = 'python' res = words.ljust(10,'*') print(res) #rjust 使用指定字符填充字符串,原有内容居右显示
words = 'python' res = words.rjust(10,'*') print(res) #strip 去掉字符左右两侧指定的字符,默认去点空格
words = '**python**' resj = words.strip('*') print(resj) #lstrip 去掉字符左侧指定的字符,默认去点空格
words = '**python**' resj = words.lstrip('*') print(resj) #rstrip 去掉字符右侧指定的字符,默认去点空格
words = '**python**' resj = words.rstrip('*') print(resj) #maketrans() 制做转换字典(只能单个字符)
trans_dict = ''.maketrans({ 'a':'85-100', 'b':'70-85', 'c':'60-70', 'd':'0-60' }) print(trans_dict) #translate() 替换字符串操做
word = '小明a小红b小张c小fd' res = word.translate(trans_dict) print(res)
相关文章
相关标签/搜索