簡體   English   中英

Python:比較兩個不完全匹配的字符串

[英]Python: Comparing two strings that are not exact match

我想比較 Python 中的兩個字符串,其中:

string1 = 'yymm_employeenumber_Employee Name' 
# Example: 2203_1145_John Doe

string2 = 'employeenumber_Employee Name'
# Example: 1145_John Doe

如何忽略 string1 中的yymm_字符和員工姓名中的空格?

對於這樣的情況,通常最好定義一個可以處理比較的自定義類,例如:

class Employee:
    def __init__(self, yymm, employee_number, employee_name):
        self.yymm = yymm
        self.employee_number = employee_number
        self.employee_name = employee_name
        
    def __str__(self):
        if self.yymm:
            return f"{self.yymm}_{self.employee_number}_{self.employee_name}"
        return f"{self.employee_number}_{self.employee_name}"
        
    def __eq__(self, other):
        # Since we are ignoring yymm, don't compare it in eq
        return self.employee_number == other.employee_number and self.employee_name == other.employee_name
        
employee1 = Employee("2203", "1145", "John Doe")
employee2 = Employee(None, "1145", "John Doe")
print(employee1 == employee2)
print(employee1)
print(employee2)

這個的輸出將是

True
2203_1145_John Doe
1145_John Doe

如果確實需要從字符串表示中解碼類,可以添加以下方法:

def load_from_string(employee_string):
    # Assuming the format is always yymm_number_name OR number_name
    # If it's not, this doesn't work
    split_string = employee_string.split("_")
    if len(split_string) == 2:
        return Employee(None, split_string[0], split_string[1])
    return Employee(split_string[0], split_string[1], split_string[2])

然后運行

employee1 = load_from_string("2203_1145_John Doe")
employee2 = load_from_string("1145_John Doe")

print(employee1 == employee2)
print(employee1)
print(employee2)

會回來

True
2203_1145_John Doe
1145_John Doe

在任何情況下,都應該使用該類。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM