首页 > 解决方案 > 将字符串的数字替换为其他数字

问题描述

我有点卡在这个问题上

我有一个只有 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)  

标签: pythonstringloops

解决方案


问题

这是您正在使用的代码:

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)


推荐阅读