[英]Comparing strings not working
我有一個存儲在文本文件中並加載到列表中的文章標題列表。 我正在嘗試將當前標題與該列表中的所有標題進行比較,如下所示
def duplicate(entry):
for line in posted_titles:
print 'Comparing'
print entry.title
print line
if line.lower() == entry.title.lower()
print 'found duplicate'
return True
return False
我的問題是,這永遠不會返回true。 當它為entry.title
和line
輸出相同的字符串時,不會將它們標記為相等。 是否有字符串比較方法或我應該使用的東西?
編輯在查看了字符串的表示形式之后, repr(line)
所比較的字符串如下所示:
u"Some Article Title About Things And Stuff - Publisher Name"
'Some Article Title About Things And Stuff - Publisher Name'
如果您提供了一個實際的示例,則將提供更多幫助。
無論如何,您的問題是Python 2中的字符串編碼不同entry.title
顯然是一個unicode字符串(用引號引起來的u
表示),而line
是普通的str
(反之亦然)。
對於以兩種格式均等表示的所有字符(ASCII字符,可能還有更多),相等性比較將成功。 對於其他字符,它將不會:
>>> 'Ä' == u'Ä'
False
當以相反的順序進行比較時,IDLE實際上會在此處發出警告:
>>> u'Ä' == 'Ä'
Warning (from warnings module):
File "__main__", line 1
UnicodeWarning: Unicode equal comparison failed to convert both arguments to Unicode - interpreting them as being unequal
False
通過使用str.decode
並提供原始編碼,可以從普通字符串中獲得unicode字符串。 例如我的IDLE中的latin1
:
>>> 'Ä'.decode('latin1')
u'\xc4'
>>> 'Ä'.decode('latin1') == u'Ä'
True
如果您知道它是utf-8,則也可以指定它。 例如,以下用utf-8保存的文件也將打印True:
# -*- coding: utf-8 -*-
print('Ä'.decode('utf-8') == u'Ä')
==
適合字符串比較。 確保您正在處理字符串
if str(line).lower() == str(entry.title).lower()
其他可能的語法是布爾表達式str1 is str2
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.