首页 > 解决方案 > 如何在python2中对不同类型的不同字符串进行操作?

问题描述

当其中一个是 str 类型而另一个是 unicode 类型时,对字符串执行操作是否错误?

例子:

image_url = u"http://sample.com"

# since the iamge url is an unicode string

if image_url.startswith("//"):
    image_url = "https://" + image_url    // combining str type with a unicode string

或者

image_url = "http://sample.com"
if image_url.startswith(u"//"):
    image_url = "https://" + image_url

或者

image_url = "http://sample.com"
if image_url.startswith("//"):
    image_url = u"https://" + image_url

或使用正则表达式替换字符串:

cleaned_breadcrumb = re.sub(r"[^A-Za-z0-9>|]+", u"", u"sample text")

或者

cleaned_breadcrumb = re.sub(r"[^A-Za-z0-9>|]+", "", u"sample text")

或者

cleaned_breadcrumb = re.sub(r"[^A-Za-z0-9>|]+", u"", "sample text")

或者

d = {u"one":"two"}

if "one" in d:
    print("yes")

标签: stringpython-2.7

解决方案


两者都是 的子类BaseString,所以不是。正如您所发现的,混合类型的表达式将被强制转换为 unicode。虽然没有错,但可能会导致一些意外,尤其是在对文件进行文本 IO 时。这两个惊喜都是 Python 2 字符串中数据的模棱两可性质所固有的。唯一完整的解决方案是迁移到 Python 3。


推荐阅读