如何在python中找到字符串中第一个非空白字符的索引?

2024-10-06 11:23:49 发布

您现在位置:Python中文网/ 问答频道 /正文

情景:

>>> a='   Hello world'
index = 3

在本例中,“H”索引为“3”。但我需要一个更通用的方法,这样对于任何字符串变量“a”的取值,我都需要知道第一个字符的索引?

替代方案:

>>> a='\tHello world'
index = 1

Tags: 方法字符串helloworldindex方案字符情景
3条回答

如果你是说第一个非空白字符,我会用这样的。。。

>>> a='   Hello world'
>>> len(a) - len(a.lstrip())
3

另一个有趣的是:

>>> sum(1 for _ in itertools.takewhile(str.isspace,a))
3

但我敢打赌,第一个版本速度更快,因为它基本上只在C中执行这个循环——当然,完成后它需要构造一个新字符串,但这基本上是免费的。


为完整起见,如果字符串为空或完全由空白组成,则这两个字符串都将返回len(a)(如果尝试用它编制索引,则无效…)

>>> a = "foobar"
>>> a[len(a)]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: string index out of range

您还可以尝试:

a = '   Hello world'
a.index(a.lstrip()[0])
=> 3

只要字符串至少包含一个非空格字符,它就可以工作。我们可以更仔细一点,在这之前检查一下:

a = '    '
-1 if not a or a.isspace() else a.index(a.lstrip()[0])
=> -1

使用regex

>>> import re
>>> a='   Hello world'
>>> re.search(r'\S',a).start()
3
>>> a='\tHello world'
>>> re.search(r'\S',a).start()
1
>>>

函数处理字符串为空或仅包含空格时的情况:

>>> def func(strs):
...     match = re.search(r'\S',strs)
...     if match:
...         return match.start()
...     else:
...         return 'No character found!'
...     
>>> func('\t\tfoo')
2
>>> func('   foo')
3
>>> func('     ')
'No character found!'
>>> func('')
'No character found!'

相关问题 更多 >