Reputation: 4557
Original string looks like this:
a,b,c,d,e
How can I replace the comma separated value that comes after the Nth comma?
So for example how can i replace the value that comes after 3rd comma with x
to create a following string?
a,b,c,x,e
Upvotes: 0
Views: 241
Reputation: 10819
The code I am posting here should be self-explanatory, if not, feel free to ask for explanations with a comment.
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'
Upvotes: 0
Reputation: 27516
It depends how you want to do it, there are several ways, e.g.:
using split
list = "a,b,c,d,e".split(",")
list[3] = "x"
print ",".join(list)
using regex
import re
print re.sub(r"^((?:[^,]+,){3})([^,]+)(.*)$", "\\1x\\3", "a,b,c,d,e")
in the regexp example, {3}
is how many entries to skip
Upvotes: 1
Reputation: 8576
mystr = 'a,b,c,d,e'
mystr = mystr.split(',')
mystr[3] = 'x'
mystr = ','.join(mystr)
print mystr
Upvotes: 1
Reputation: 257
Yes It is possible
def replaceNthComma(data, indexOfComma, newVal):
_list = list(data)
_list[indexOfComma*2] = newVal
return ''.join(_list)
Which will return the exact ouput as you expect.
ouput: replaceNthComma("a,b,c,x,e", 3, 'x') ==> 'a,b,c,x,e'
Upvotes: 0