如何仅替换列表中每个字符串的首个'1'为'0'?现有代码替换全部字符
Got it, let's sort out this issue! The problem with your current code is that the str.replace('1', '0') method replaces all instances of '1' with '0' in each string, but you only want to swap the first occurrence. Here's how to fix it step by step:
What's Wrong with the Original Code?
Your list comprehension line:
d = [s.replace('1', '0') for s in d]
uses replace() without specifying a replacement count, so it defaults to replacing every matching character. That's why you're getting all '1's turned to '0's instead of just the first one.
Updated Solution Code
We'll use the third parameter of str.replace() to limit replacements to just the first occurrence (or the number specified in your input's second value, b):
a, b = input().split() a = int(a) b = int(b) # Convert the change count to an integer d = [] # No need for global variables—just collect inputs directly into the list for _ in range(a): user_input = input("Enter something: ") d.append(user_input) # Replace only the first '1' (or up to 'b' times, per your input) d = [s.replace('1', '0', b) for s in d] # Print each result on a new line to match your expected output for result in d: print(result)
Key Changes Explained:
- Limited Replacements: The
replace('1', '0', b)call usesb(your input's second value, which is 1 here) to restrict replacements to just the first '1' in each string. If you ever need to replace more than one (e.g.,b=2), this will automatically handle that too. - Simplified Input Collection: Removed the unnecessary
globals()usage—you don't need to create named variables likeside1orside2; just append each input directly to your listd. - Clean Output: Instead of printing the entire list, we loop through and print each string on its own line, which matches your expected output format exactly.
Test with Your Example Input
If you run the code with this input:
4 1 0101 0010 0100 1000
You'll get the desired output:
0001 0000 0000 0000
内容的提问来源于stack exchange,提问作者Orest.Korol

