首页 > 解决方案 > 如何在python中比较两个不同编码的字符串?

问题描述

语境:

我正在从编码的 txt 文件中提取字符串'utf-8', application_name = 'MicrosoftEdge'

然后我使用 python ctypes 模块来确定当前活动的应用程序 window = curr_application

user32 = ctypes.WinDLL('user32', use_last_error=True)
curr_window = user32.GetForegroundWindow()
window_name = str(win32gui.GetWindowText(curr_window))
rev = window_name[::-1]
pos = rev.find("-")
curr_application = rev[0:pos][::-1].replace(" ","")

这也返回:'MicrosoftEdge'

但是当我这样做时:

print(curr_application == application_name)

它总是返回False

这是我得到的输出:

>>> print(application_name.encode())
b'MicrosoftEdge\n'
>>> print(curr_application.encode())
b'Microsoft\xe2\x80\x8bEdge'

我的问题是,我应该怎么做才能在比较两个字符串时得到真实的结果?

标签: pythonstringencodingctypes

解决方案


更新:

这对我有用:

import string
allowed_chars = string.ascii_letters
application_name = 'MicrosoftEdge'
curr_application = 'Microsoft\xe2\x80\x8bEdge'
application = ""
for letter in curr_application:
    if letter in allowed_chars:
        application = application + letter
print(application==application_name)

然后返回True


推荐阅读