替换字符串中出现的字符跳过第一个出现的字符

2024-09-30 01:34:07 发布

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

用空格()替换&的出现处,但第一个出现处除外

a = "abc&def&hij&klm"
output = abc&def hij klm"

remove&多次出现,并在其中放置一个空格


Tags: outputdefremove空格abchijklm
3条回答
a="abc&def&hij&klm"

# split based on & character
res = a.split('&', 1)

# replace & with space in 2nd element  
res[1] = res[1].replace('&', ' ')

# now join list into string
print '&'.join(res)

使用字符串滑动:

ind = a.index('&')
a = a[:ind+1] + a[ind+1:].replace('&', ' ')
  1. 发现第一次发生
  2. 在索引+1上滑动
  3. 替换第二部分中char的所有条目

简单方法:

output = '&'.join(s.replace('&', ' ') for s in a.split('&', 1))

相关问题 更多 >

    热门问题