python 基础学习 (三)

发布于 更新于

技术文章测试开发

字符串 一、创建(增)

字符串 一、创建(增)

name1 = "python56" name2 = 'python56' name3 = python56 name4 = '''python56''' name5 = ''

二、访问(查询) 1、通过索引访问(索引从0开始)正序索引从左往右数 name1[index] 如果索引值超过字符长度会报错:IndexError: string index out of range 2、倒序索引(索引从-1开始)倒序索引从右往左数 print(name1[-1]) 3、通过元素值取索引值 name1.index('n') 如果元素不存在会报错:ValueError: substring not found 4、获取字符串的长度 print(len(test_str)) 5、切片【掌握】 语法:字符串[起始索引值:结束索引值:步长] 注意点: 1、取值原则,左闭右开,包含左边的索引值,不包含右边的索引值 2、如果起始索引值不写,默认为0(缺省值) 3、如果结束索引不写,默认为字符串的长度 4、步长如果不写,默认是1,为正确切片 5、一个空格也占一个索引位置 6、正序切片用正序索引,倒序切片用倒序索引 7、会用正序切片就行,倒序切片做了解 6、字符串倒序 result = test_str[::-1]

7、字符串运算 字符串连接(+):

test_str1 = "hello" test_str2 = "python" print(test_str1+" "+test_str2)

重复输出: test_str1 = "hello" print(test_str1*10)

成员运算【掌握】: in not in test_str1 = "hello" result1 = 'w' in test_str1 result2 = 'w' not in test_str1 print(result1,result2)

身份运算【掌握】: test_str1 = "hello" test_str2 = test_str1 print(test_str2 is test_str1) is 的区别 对比的是值,is对比的是内存地址

8、字符串转义字符【掌握】 1、:res = "D:\name.png" 2、r: res = r"D:\name.png"

三、修改(改) -- 不支持 四、删除(删) -- 不支持

五、常用的方法 单词大小写相关的方法 1、result = test_str.upper() 所有字母大写 2、result2 = result.lower() 所有字母小写 3、result3 = test_str.capitalize() 字符串首字母大写 4、result4 = test_str.swapcase() 大小写互换 5、result5 = test_str.title() 每个单词的首字母大写

统计相关的方法 1、result = test_str.count('h') 统计字符串出现的次数,可以指定统计范围,缺省是在整个字符串中统计 sub: 需要统计的字符串 __start: 统计的起始索引位置 __end: 统计结束的索引位置

2、result = test_str.find('h',3,10) sub: 需要查找的字符串,返回索引值 __start: 查找的起始索引位置 __end: 查找结束的索引位置

3、找最后一个的索引值 sub: 需要查找的字符串,返回索引值 __start: 查找的起始索引位置 __end: 查找结束的索引位置 result2 = test_str.rfind('h')

判断相关的方法 1、result1 = test_str.islower(): 判断是否都是小写,返回布尔值 2、result2 = test_str.isupper(): 判断是否都是大写,返回布尔值 3、result3 = test_str.isalnum(): 判断是否由字母或者数字或者中文 4、result4 = test_str.isdigit(): 判断字符串是否都由数字组成 5、result5 = test_str.startswith('h'): 判断是否是以h开头 6、result6 = test_str.endswith('4'): 判断是否是以4结尾

来源:testingpai

继续阅读