繁体   English   中英

如何使用Python startwith方法将unicode和ascii字符串组合?

[英]How to use Python startswith method for combination of unicode and ascii string?

就我而言,当我使用时,我将Unicode text_string和前缀作为ASCII字符串

text-string.startswith(prefix) 

我以这种方式得到一个例外

UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 9: ordinal not in range(128)

如何比较两个字符串,我尝试使用unicode(string)方法将ASCII字符串转换为Unicode,但仍然遇到相同的异常。

如何解决呢? 在最坏的情况下,如何在比较时抑制此异常?

text - u'PreciChrom I/II is a lyophilized control based on human citrated plasma.'
prefix - 'Reagents – working solutions'

您的前缀字符串不是 ASCII。 如错误消息所述,您在位置9有非ASCII字符; 破折号 该字符串可能是utf-8。

您可以将前缀解码为unicode:

text_string.startswith(prefix.decode('utf-8'))

text_string.encode().startswith(prefix)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM