0

I need to change the first occurrence of a 1 into a 0 for each element of a string in list, but it changes everything:

a, b = input().split()
a = int(a)
d=[]
for x in range(1,a+1):
    globals()['side%s' % x] = input("Enter something: ")
    d.append(globals()['side%s' % x])

d = [s.replace('1', '0') for s in d]


print(d)

Example:

4 1 // 4 number of inputs, 1 - number of possible changes to string

0101
0010
0100
1000

need to be

0001
0000
0000
0000
4
  • Can you better explain what you are trying to achieve. Commented May 21, 2018 at 6:25
  • 1
    If I understand correctly, you only want to replace the first occurence of a 1 with 0 and leave the other occurences unchanged? Commented May 21, 2018 at 6:27
  • Yes, only one occurence in each item Commented May 21, 2018 at 6:30
  • @Bad.coder This is a duplicate of stackoverflow.com/questions/4628618/…. Answer: replace() takes an optional third argument, the maximum number of times to replace. For example, replace('1', '0', 1) will perform the replacement on only the first instance Commented May 21, 2018 at 6:32

1 Answer 1

1

since you want x number of occurrence to be replaced, the replace function offers this string.replace(s, old, new[, maxreplace]), you might want to pass on b which is the maxreplace as the third parameter.

a, b = input().split()
a = int(a)
d=[]
for x in range(1,a+1):
    globals()['side%s' % x] = input("Enter something: ")
    d.append(globals()['side%s' % x])

d = [s.replace('1', '0', int(b)) for s in d] # maxreplace will be b only


print(d)
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.