You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何仅替换列表中每个字符串的首个'1'为'0'?现有代码替换全部字符

Fix: Replace Only the First '1' in Each String

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 uses b (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 like side1 or side2; just append each input directly to your list d.
  • 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 07:17:44