Python 替换第n个分隔符后的值

Python 替换第n个分隔符后的值,python,string,python-3.x,Python,String,Python 3.x,原始字符串如下所示: a,b,c,d,e 如何替换第n个逗号后的逗号分隔值 例如,我如何用x替换第三个逗号后面的值来创建以下字符串 a、b、c、x、e是的,这是可能的 def replacenthcoma(数据、indexOfComma、newVal): _列表=列表(数据) _列表[indexOfComma*2]=newVal 返回“”。加入(\u列表) 它将返回您期望的确切输出 output:replacenthcoma(“a,b,c,x,e”,3,'x')==>a,b,c,x,e'是的,

原始字符串如下所示:

a,b,c,d,e
如何替换第n个逗号后的逗号分隔值

例如,我如何用
x
替换第三个逗号后面的值来创建以下字符串

a、b、c、x、e
是的,这是可能的

def replacenthcoma(数据、indexOfComma、newVal):
_列表=列表(数据)
_列表[indexOfComma*2]=newVal
返回“”。加入(\u列表)

它将返回您期望的确切输出

output:replacenthcoma(“a,b,c,x,e”,3,'x')==>a,b,c,x,e'
是的,这是可能的

mystr = 'a,b,c,d,e'

mystr = mystr.split(',')
mystr[3] = 'x'
mystr = ','.join(mystr)

print mystr
def replacenthcoma(数据、indexOfComma、newVal):
_列表=列表(数据)
_列表[indexOfComma*2]=newVal
返回“”。加入(\u列表)

它将返回您期望的确切输出


output:replacenthcoma(“a,b,c,x,e”,3,'x')==>“a,b,c,x,e”

这取决于你想怎么做,有几种方法,例如:

mystr = 'a,b,c,d,e'

mystr = mystr.split(',')
mystr[3] = 'x'
mystr = ','.join(mystr)

print mystr
使用拆分

list = "a,b,c,d,e".split(",")
list[3] = "x"
print ",".join(list)
使用正则表达式

import re
print re.sub(r"^((?:[^,]+,){3})([^,]+)(.*)$", "\\1x\\3", "a,b,c,d,e")

在regexp示例中,
{3}
是要跳过多少个条目

这取决于您希望如何执行,有几种方法,例如:

使用拆分

list = "a,b,c,d,e".split(",")
list[3] = "x"
print ",".join(list)
使用正则表达式

import re
print re.sub(r"^((?:[^,]+,){3})([^,]+)(.*)$", "\\1x\\3", "a,b,c,d,e")

在regexp示例中,
{3}
是要跳过多少个条目

我在这里发布的代码应该是自解释的,如果不是,请随意要求解释并添加注释

s = 'a,b,c,d,e'
n = 3
to_replace_with = 'x'

l = s.split(',')
l[n] = to_replace_with
result = ','.join(l)

>>>print(result)
'a,b,c,x,e'

我在这里发布的代码应该是不言自明的,如果不是,请随时要求解释并发表评论

s = 'a,b,c,d,e'
n = 3
to_replace_with = 'x'

l = s.split(',')
l[n] = to_replace_with
result = ','.join(l)

>>>print(result)
'a,b,c,x,e'