python - 将字符串的数字替换为其他数字
问题描述
我有点卡在这个问题上
我有一个只有 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)
解决方案
问题
这是您正在使用的代码:
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)
推荐阅读
- r - 为 R 中不同时间点的多列生成斜率
- angular - ERROR 错误:未捕获(承诺中):InvalidCharacterError:无法在“窗口”上执行“atob”:要解码的字符串未正确编码
- excel - 如何在 Excel 单元格中添加一个常数因子作为输出?
- visual-studio - Visual Studio:如何按顺序链接多个项目?
- javascript - 如何为 JavaScript 中对象数组中特定元素的属性赋值?
- android - firebase 连接在设备中不起作用,但在模拟器中起作用
- python - 使用 tkinter 如何让一组坐标始终更新?
- android - 对 Android Telecom 子系统来电事件的顺序感到困惑
- javascript - 用地图反应复杂的过滤器
- powershell - 运行空间:EndInvoke() 未能返回所有脚本块输出,仅返回最后一个异常