【问题标题】:replace digits of a string into others将字符串的数字替换为其他数字
【发布时间】:2021-11-02 06:06:13
【问题描述】:

我有点被这个问题困扰

我有一个只有 1 和 0 的字符串 我正在尝试将每个“0”变成“10”,将每个“1”变成“01”

我对使用 replace() 函数不感兴趣

我试过了,但它只是把'1'变成'01',我不知道为什么'0'没有改变,有人知道为什么吗?谢谢!

mystring='010101'

for i in mystring:
    if(i=='0'):
        i=='01'
    else:
        i='10'
    print(i)  

【问题讨论】:

  • 您正在使用变量 i 迭代字符串并替换相同的变量

标签: python string loops


【解决方案1】:

问题

这是您正在使用的代码:

mystring='010101'

for i in mystring:
    if(i=='0'):
        i=='01' # This is a comparing operator and this returns false but as you havnt given the variable where it should store the false value. And so I remains unchanged.
    else:
        i='10'
    print(i)  

解决方案

这是因为您使用的是比较运算符而不是分配运算符。

mystring = "010101"

for i in mystring:
    if i == "0":
        i = "01" # Use assignment operators instead of comparing operators
    else:
        i = "10"
    print(i)

【讨论】:

    【解决方案2】:

    我们可以在这里使用带有回调函数的re.sub

    mystring = '010101'
    output = re.sub(r'[01]', lambda m: '10' if m.group() == '0' else '01', mystring)
    print(output)  # 100110011001
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-08-30
      • 2017-12-17
      • 1970-01-01
      • 2021-03-11
      • 2017-01-02
      • 2023-03-30
      • 1970-01-01
      • 2013-11-08
      相关资源
      最近更新 更多