Ale*_*lex 47 python string whitespace
Python的string.whitespace很棒:
>>> string.whitespace
'\t\n\x0b\x0c\r '
Run Code Online (Sandbox Code Playgroud)
如何使用字符串而无需手动输入'\ t | \n | ...等正则表达式?
例如,它应该能够变成:"请不要伤害我."
成
"请不要伤害我."
我可能想要保留单个空格,但是我觉得很容易就去string.whitespace [: - 1].
bob*_*nce 144
这个用例有一个特例快捷方式!
如果你在str.split没有参数的情况下调用,它会在空格而不是单个字符的运行上进行分割.所以:
>>> ' '.join("Please \n don't \t hurt \x0b me.".split())
"Please don't hurt me."
Run Code Online (Sandbox Code Playgroud)
Imr*_*ran 13
什么是错误的\s字符类?
>>> import re
>>> pattern = re.compile(r'\s+')
>>> re.sub(pattern, ' ', "Please \n don't \t hurt \x0b me.")
"Please don't hurt me."
Run Code Online (Sandbox Code Playgroud)
让我们做一些合理的假设:
(1)你真的想用一个空格(一个长度为1或更大的行)替换任何空格字符.
(2)您希望使用相同的代码在Python 2.X下使用unicode对象进行最小的更改.
(3)您不希望您的代码承担文档中无法保证的内容
(4)您希望使用相同的代码处理Python 3.X str对象的最小更改.
当前选择的答案存在以下问题:
(a)更改" " * 3为" " * 2即删除重复空格但不删除一式三份,一式四份等空格.[失败要求1]
(b)"foo\tbar\tzot"对"foobarzot"[未通过要求1]的修改
(c)当输入unicode对象时,得到TypeError: translate() takes exactly one argument (2 given)[失败要求2]
(d)使用string.whitespace[:-1][未通过要求3; string.whitespace中的字符顺序不保证]
(e)使用string.whitespace[:-1][未通过要求4; 在Python 2.X中,string.whitespace是'\t\n\x0b\x0c\r '; 在Python 3.X中,它是'\ t \n\r\x0b\x0c']
的" ".join(s.split())回答与re.sub(r"\s+", " ", s)答案不存在这些问题.