当字符串匹配时,替换字符串中的所有内容

2024-09-30 18:30:41 发布

您现在位置:Python中文网/ 问答频道 /正文

鉴于:

path = 'abc/dfg/zxc'

有没有办法将第一个“/”前面的字符串替换为“.”

预期结果:

'./dfg/zxc'

我已经尝试过,这种方法很混乱,我想知道是否有一种更干净的方法来解决这个问题

 lst = path.split()

from_index = lst[0].index('/')
to_index = len(lst[0])

new_list = lst[0][from_index -1 + 1:to_index]
new_str = ''.join(new_list)
new_str2 = '.' + new_str

Tags: topath方法字符串fromnewindexlist
3条回答

使用正则表达式匹配/替换如何

import re

path = 'abc/dfg/zxc'

print(re.sub(r'^\w+/', './', path))
'./dfg/zxc'

这是一种使用^{}方法的方法:

path = f"./{path.split('/',1)[1]}"

print(path)

输出:

'./dfg/zxc'

你应该这样做:

path = path.replace(path[0:path.find("/")], ".")

相关问题 更多 >