string - 如何在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")
解决方案
两者都是 的子类BaseString
,所以不是。正如您所发现的,混合类型的表达式将被强制转换为 unicode。虽然没有错,但可能会导致一些意外,尤其是在对文件进行文本 IO 时。这两个惊喜都是 Python 2 字符串中数据的模棱两可性质所固有的。唯一完整的解决方案是迁移到 Python 3。
推荐阅读
- python - 如何在 Python 中求解这些非线性方程?
- pointers - 如何将字符返回给 c 中的调用函数以及我的代码有什么问题?
- python - Airflow XCOM pull 不渲染
- python - 有什么方法可以使用 pydantic BaseModel 创建父属性?
- opencv-solvepnp - 当目标点以 ecef 世界坐标表示时,tvec 的输出是什么?
- java - @Autowired 在 Java 中到底是什么意思?
- c# - 数据库操作预计会影响 1 行,但实际上影响了非主键上的 0 行
- metrics - 如何计算 Google Data Studio 上两个指标的总和之间的比率?
- c# - 带有谷歌表单的 Httpwebrequest(GoogleFormsToolkitLibrary)
- arrays - 在 C 中删除具有 char 数组成员的结构数组中的项目