python-3.x - 如何用 if else 语句表示之前和之后
问题描述
我想告诉python字符串中某个字符之前的所有内容都等于其他内容。在这段代码中,我希望将等号之后的所有内容分配给一个名为 results 的单独列表,并将等号之前的所有内容分配给一个名为 names 的整个其他列表。
我相信需要一个 if/else 语句,但我不知道如何在 python 中表示 BEFORE 和 AFTER。
lines = ['Data1 = 100',
'Data2 = TRUE',
'Data3 = 45',
'Data4 = False',
]
解决方案
您可以使用 list() 函数。它将字符串拆分为字符。您的问题是,您必须事先指定角色出现次数的位置才能获得开始和停止位置。
如果您确切知道要替换的内容,则另一种选择是使用 str.replace() ,但这两种方法都存在硬编码的问题。如果您只想在条件语句中替换它们,这些可能很有用。
为了您的使用,您可以说类似
loop through array.
split the element in the array using split
add logic statement that if array[i-1] == "=", start replacing elements with new element
then add the new element back into the array at the position you removed wanted to be removed.
推荐阅读
- spring-boot - 弹簧反应的弹簧安全会话超时
- javascript - 在Javascript中打印所有带有索引的ASCII字符
- android - Firebase 动态链接广告系列跟踪不起作用
- android - 专注于两个小部件 - Android
- javascript - 隐藏 iframe 但以某种方式解除它
- javascript - 有没有办法使用 toHaveBeenCalledWith 来检查参数数组长度?
- python - 在 Python 中使用 FP-Growth 算法来确定最频繁的模式
- flutter - Flutter 和应用程序捆绑 google play store 上传限制
- html - 如何为使用 *ngFor 生成的最后一个角度组件(列表组项)添加边框
- mongodb - 具有两个值的 MongoDB 分页