首页 > 解决方案 > 如何用 if else 语句表示之前和之后

问题描述

我想告诉python字符串中某个字符之前的所有内容都等于其他内容。在这段代码中,我希望将等号之后的所有内容分配给一个名为 results 的单独列表,并将等号之前的所有内容分配给一个名为 names 的整个其他列表。

我相信需要一个 if/else 语句,但我不知道如何在 python 中表示 BEFORE 和 AFTER。

lines = ['Data1         = 100',
         'Data2         = TRUE',
         'Data3         = 45',
         'Data4         = False',
         ]

标签: python-3.x

解决方案


您可以使用 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.

推荐阅读