[英]Which specific characters does the strip function remove?
您可以在str.strip
文档中找到以下内容:
chars参数是一个字符串,指定要删除的字符集。 如果省略或
None
,则chars参数默认为删除空格。
现在我的问题是:哪些特定字符被视为空格?
这些 function 调用共享相同的结果:
>>> ' '.strip()
''
>>> '\n'.strip()
''
>>> '\r'.strip()
''
>>> '\v'.strip()
''
>>> '\x1e'.strip()
''
在这个相关问题中,一位用户提到str.strip
function 使用 ASCII 空白字符的超集(换句话说, string.whitespace
的超集)。 更具体地说,它适用于所有 unicode 空白字符。
此外,我相信(但我只是猜测,我没有证据) c.isspace()
为每个字符c返回True
,这些字符也将被str.strip
删除。 那是对的吗? 如果是这样,我想可以只为每个 unicode 字符c运行str.strip
c.isspace()
,并提供一个默认删除的空白字符列表。
>>> ' '.isspace()
True
>>> '\n'.isspace()
True
>>> '\r'.isspace()
True
>>> '\v'.isspace()
True
>>> '\x1e'.isspace()
True
我的假设正确吗? 如果是这样,我怎样才能找到一些证据? 有没有更简单的方法可以知道str.strip
自动删除了哪些特定字符?
了解str.strip()
删除哪些字符的最简单方法是遍历每个可能的字符并检查包含此类字符的字符串是否被str.strip()
更改:
c = 0
while True:
try:
s = chr(c)
except ValueError:
break
if (s != s.strip()):
print(f"{hex(c)} is stripped", flush=True)
c+=1
正如评论中所建议的,您还可以打印一个表格来检查str.strip()
、 str.split()
和str.isspace()
共享关于空白的相同行为:
c = 0
print("char\tstrip\tsplit\tisspace")
while True:
try:
s = chr(c)
except ValueError:
break
stripped = s != s.strip()
splitted = not s.split()
spaced = s.isspace()
if (stripped or splitted or spaced):
print(f"{hex(c)}\t{stripped}\t{splitted}\t{spaced}", flush=True)
c+=1
如果我运行上面的代码,我会得到:
char strip split isspace
0x9 True True True
0xa True True True
0xb True True True
0xc True True True
0xd True True True
0x1c True True True
0x1d True True True
0x1e True True True
0x1f True True True
0x20 True True True
0x85 True True True
0xa0 True True True
0x1680 True True True
0x2000 True True True
0x2001 True True True
0x2002 True True True
0x2003 True True True
0x2004 True True True
0x2005 True True True
0x2006 True True True
0x2007 True True True
0x2008 True True True
0x2009 True True True
0x200a True True True
0x2028 True True True
0x2029 True True True
0x202f True True True
0x205f True True True
0x3000 True True True
因此,至少在 python 3.10.4 中,您的假设似乎是正确的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.