python特定位置的字符串截取

1,index

img_path = "camel.png"
img_name = img_path[:-4]  # 通过索引截取camel

2,str.rfind(str, beg=0 end=len(string))

str = "this is really a string - example"
substr1 = "really"
substr2 = "_"

str[:str.rfind(substr1)]  # 截取this is

3,find() 是从字符串左边开始查询子字符串匹配到的第一个索引

rfind()是从字符串右边开始查询字符串匹配到的第一个索引

# img_list[i] = 'EU_155_12_4_mask.png'
img_list[i].split('_') # : ['EU', '155', '12', '4', 'mask.png']
img_list[i].split('_', 1) # : ['EU', '155_12_4_mask.png']

4,骚操作,字符替换

# img_list[i] = 'EU_155_12_4_mask.png'

img_list[i].replace("_12_", "_6_")

# img_list[i] = 'EU_155_6_4_mask.png'

 

你可能感兴趣的:(Python)