1. 程式人生 > 其它 >Python----字串擷取(查詢,替換)

Python----字串擷取(查詢,替換)

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]