2013-07-03 42 views
-2

對python.I新的我想比較兩個字符串,但它們中的數字應該被忽略。在比較字符串時忽略數字

例如,要比較 「addf.0987.addf」 與「addf.1222.addf」

u能幫助

+0

我建議你一個Python代碼添加到這一點,除非你真的想在任何語言 – doctorlove

+0

幫助的答案什麼?在尋求幫助之前你有嘗試過什麼嗎? – Blender

+0

那麼,你的例子應該返回True? – TerryA

回答

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 
+0

這很好!我以前沒見過'all()' - 謝謝 –

+0

@NickBurns;).. – TerryA

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. 
0

P ython有比較字符串或字符串切片的簡單而優雅的方法(例如參見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)

+0

謝謝大家。對不完整的問題抱歉.....我用all()。 – Praway