尽管文档表明它们应该相同,strip() 和 strip(string.whitespace) 给出了不同的结果 [英] strip() and strip(string.whitespace) give different results despite documentation suggesting they should be the same

查看:26
本文介绍了尽管文档表明它们应该相同,strip() 和 strip(string.whitespace) 给出了不同的结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 Unicode 字符串,开头和结尾都有一些不间断的空格.使用 strip()strip(string.whitespace) 时,我得到了不同的结果.

<预><代码>>>>导入字符串>>>s5 = u'\xa0\xa0hello\xa0\xa0'>>>打印 s5.strip()你好>>>打印 s5.strip(string.whitespace)你好

strip() 的文档说,如果省略或 Nonechars 参数默认为删除空格."string.whitespace 的文档说,包含所有被视为空白的字符的字符串."

那么如果 string.whitespace 包含所有被认为是空白的字符,那么为什么结果不同?和Unicode有关系吗?

我使用的是 Python 2.7.6

解决方案

来自 的文档string.whitespace:

<块引用>

包含所有被考虑的ASCII字符的字符串空白.这包括字符空格、制表符、换行符、回车、换页和垂直制表符.

python3 下也是一样,所有非 ASCII 常量都被删除了.(在 python2 中,一些常量可能会受到 locale 设置的影响).

因此行为上的差异非常明显,因为 strip() 确实 删除了任何 unicode 空格,而 strip(string.whitespace) 仅删除 ASCII 空格.您的字符串显然包含非 ASCII 空格.

I have a Unicode string with some non-breaking spaces at the beginning and end. I get different results when using strip() vs. strip(string.whitespace).

>>> import string
>>> s5 = u'\xa0\xa0hello\xa0\xa0'
>>> print s5.strip()
hello
>>> print s5.strip(string.whitespace)
  hello  

The documentation for strip() says, "If omitted or None, the chars argument defaults to removing whitespace." The documentation for string.whitespace says, "A string containing all characters that are considered whitespace."

So if string.whitespace contains all characters that are considered whitespace, then why are the results different? Does it have something to do with Unicode?

I am using Python 2.7.6

解决方案

From the documentation of the string.whitespace:

A string containing all ASCII characters that are considered whitespace. This includes the characters space, tab, linefeed, return, formfeed, and vertical tab.

It's the same under python3, where all non-ASCII constants where removed. (In python2 some constants could be influenced by locale settings).

Hence the difference in behaviour is quite obvious since strip() does remove any unicode whitespace, while strip(string.whitespace) removes only ASCII spaces. Your string clearly contains non-ASCII spaces.

这篇关于尽管文档表明它们应该相同,strip() 和 strip(string.whitespace) 给出了不同的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆