I have the following string in python:
'this is my string (x,x,x,x)'
I want to replace each x per each number in this list:
[1,2,3,4]
So, the final output should be this:
'this is my string (1,2,3,4)'
I have tried to solve it with different approaches but I can't do it.
I don't know if there is an efficient way to do this.
asked Apr 30, 2020 at 13:40
J.C Guzman
1,3346 gold badges23 silver badges53 bronze badges
-
Please update your question with the code you have tried.quamrana– quamrana2020年04月30日 13:41:55 +00:00Commented Apr 30, 2020 at 13:41
2 Answers 2
What about this one?
'this is my string (x,x,x,x)'.replace('x','{}').format(*[1,2,3,4])
answered Apr 30, 2020 at 13:45
Halil İbrahim Yıldırım
4002 silver badges9 bronze badges
Sign up to request clarification or add additional context in comments.
1 Comment
lenik
'this is my string (x,x,x,x)'.replace('x','{}').format(*[1,2,3,4]) ?here the solution
s = 'this is my string (x,x,x,x)'
s
'this is my string (x,x,x,x)'
for i in range(1, len(s.split('x'))):
s = s.replace('x', str(i), 1)
s
'this is my string (1,2,3,4)'
to prevent malcontent
you can use
s.count('x,') + 1 instead of len(s.split('x'))
if you have x in your string
6 Comments
lenik
len(s.split('x')) -> s.count('x') ??lenik
s.count('x,') -- the last x does not have a comma afterwards.Beny Gj
@lenik that why i have added plus 1 to omit the last one
lenik
how come your code does not use the sample list
[1,2,3,4] ? please, bear in mind, that the numbers are just a place holders, the actual values can be different.Beny Gj
@lenik yea i know but , he didn't say that what the requirement , i only suggested this way , of course he can iterate on is own list
|
lang-py