8

设想:

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

在这种情况下,“H”索引是“3”。但是我需要一种更通用的方法,以便对于任何字符串变量 'a' 需要知道第一个字符的索引?

替代方案:

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

5 回答 5

8

如果你的意思是第一个非空白字符,我会使用这样的东西......

>>> 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
于 2013-06-13T14:09:37.657 回答
3

使用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!'
于 2013-06-13T14:11:06.517 回答
2

你也可以试试:

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

只要字符串包含至少一个非空格字符,它就会起作用。我们可以更加小心,并在此之前检查一下:

a = '    '
-1 if not a or a.isspace() else a.index(a.lstrip()[0])
=> -1
于 2013-06-13T14:14:44.713 回答
1

另一种方法,只是为了好玩...使用特殊功能!

>>> def first_non_space_index(s):
    for idx, c in enumerate(s):
        if not c.isspace():
            return idx


>>> a = '   Hello world'        
>>> first_non_space_index(a)
3
于 2013-06-13T14:17:13.730 回答
0

按照 mgilson 的回答,您可以使用 lstrip 删除您想要的任何字符 -

unwanted = ':!@#$%^&*()_+ \t\n'
a= '  _Hello world'
res = len(a) - len(a.lstrip(unwanted)) 
于 2013-06-13T14:19:34.203 回答