0

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.

1
  • Please update your question with the code you have tried. Commented Apr 30, 2020 at 13:41

2 Answers 2

2

What about this one?

'this is my string (x,x,x,x)'.replace('x','{}').format(*[1,2,3,4])
Sign up to request clarification or add additional context in comments.

1 Comment

'this is my string (x,x,x,x)'.replace('x','{}').format(*[1,2,3,4]) ?
-1

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

len(s.split('x')) -> s.count('x') ??
s.count('x,') -- the last x does not have a comma afterwards.
@lenik that why i have added plus 1 to omit the last one
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.
@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
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.