比较字符串时忽略数字

时间:2013-07-03 09:06:42

标签: python string compare

我是python的新手。我想比较两个字符串。但是应该忽略它们中的数字。

EG。想要将“addf.0987.addf”与“addf.1222.addf”进行比较

你可以帮忙吗?

3 个答案:

答案 0 :(得分:1)

您可以使用all()

>>> one = "addf.0987.addf"
>>> two = "addf.1222.addf"
>>> all(i[0] == i[1] for i in zip(one, two) if not i[0].isdigit())
True

或者:

>>> one = "addf.0987.addf"
>>> two = "addf.1222.addf"
>>> [i for i in one if not i.isdigit()] == [i for i in two if not i.isdigit()]
True

答案 1 :(得分:1)

在这里。

def is_equal(m, n):
    if len(m) != len(n):
        return False
    for ind in xrange(len(m)):
        if m[ind].isdigit() and n[ind].isdigit():
            continue
        if m[ind] != n[ind]:
            return False
    else:
        return True


is_equal("addf.0987.addf", "addf.1222.add")    # It returns False.
is_equal("addf.11.addf", "addf.11.addf")       # It returns True.
is_equal("addf.11.addf", "addf.22.addf")       # it returns True.

答案 2 :(得分:0)

Python具有比较字符串或字符串片段的简单而优雅的方法(例如,参见Haidro的答案)。这是我非常喜欢Python的一个方面。但如果你想要一些非常愚蠢的东西:

    a1 = 'addf.1234.addf'
    a2 = 'addf.4376.addf'
    a3 = 'xxxx.1234.xxxx'

    my_compare = lambda x: (x[:4], x[-4:])

    my_compare(a1) == my_compare(a2)
    => True
    my_compare(a1) == my_compare(a3)
    => False

(注意这只是为了好玩:p)

相关问题