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

设想:


>>> a='   Hello world'

index = 3

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


替代方案:


>>> a='\tHello world'

index = 1


心有法竹
浏览 905回答 4
4回答

手掌心

如果您是说第一个非空白字符,那么我会使用类似这样的东西...>>> a='&nbsp; &nbsp;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):&nbsp; File "<stdin>", line 1, in <module>IndexError: string index out of range

开心每一天1111

使用regex:>>> import re>>> a='&nbsp; &nbsp;Hello world'>>> re.search(r'\S',a).start()3>>> a='\tHello world'>>> re.search(r'\S',a).start()1>>>处理字符串为空或仅包含空格的情况的函数:>>> def func(strs):...&nbsp; &nbsp; &nbsp;match = re.search(r'\S',strs)...&nbsp; &nbsp; &nbsp;if match:...&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;return match.start()...&nbsp; &nbsp; &nbsp;else:...&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;return 'No character found!'...&nbsp; &nbsp; &nbsp;>>> func('\t\tfoo')2>>> func('&nbsp; &nbsp;foo')3>>> func('&nbsp; &nbsp; &nbsp;')'No character found!'>>> func('')'No character found!'

慕少森

您也可以尝试:a = '&nbsp; &nbsp;Hello world'a.index(a.lstrip()[0])=> 3只要字符串包含至少一个非空格字符,它就可以工作。我们可以更小心一点,并在进行以下检查:a = '&nbsp; &nbsp; '-1 if not a or a.isspace() else a.index(a.lstrip()[0])=> -1
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python