1. 查找(字符串第一次出現的位置)
a = 'testcases/test_ddt/test_ddt_login.py::TestDdtLogin::test_login[11111111111-\u5991\u9d25-\u8c0b5]' # 檢查字符串a中是否包含:: ,如果包含子字符串返回開始的索引值,否則返回-1 # a.find('::', 開始索引默認為0 , 結束索引默認為字符串的長度) print(a.find('+')) # -1(不包含) print(a.find('::')) # 36(包含,索引位置為36) print(a.find('::',40,len(a))) # 50 (找到第二個:: 所在的位置)
2.查找(字符串最后一次出現的位置)
a = 'testcases/test_ddt/test_ddt_login.py::TestDdtLogin::test_login[11111111111-\u5991\u9d25-\u8c0b5]' # 返回字符串最后一次出現的位置,如果沒有匹配項則返回 -1 # a.rfind('::', 開始索引默認為0 , 結束索引默認為字符串的長度) print(a.rfind('+')) # -1(不包含) print(a.rfind('::')) # 50(包含,索引位置為50) print(a.rfind('::',40,len(a))) # 50 (開始查找索引為40,找到結束)
3.替換(替換字符串中字符為指定內容)
a = 'testcases/test_ddt/test_ddt_login.py::TestDdtLogin::test_login[11...11]' # 替換字符串中字符為指定內容,如果沒有匹配項則返回 -1 # a.replace(被替換掉的字符, 新字符, 替換次數默認全部替換) print(a.replace('/','//')) # testcases//test_ddt//test_ddt_login.py::TestDdtLogin::test_login[11...11] print(a.replace('/','//',1)) # testcases//test_ddt/test_ddt_login.py::TestDdtLogin::test_login[11...11]