簡體   English   中英

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

[英]how to find the index of the first non-whitespace character in a string in python?

場景:

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

在這種情況下,“H”指數為“3”。 但是我需要一個更通用的方法,這樣對於任何字符串變量'a'需要我需要知道第一個字符的索引?

替代方案:

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

如果你的意思是第一個非空白字符,我會用這樣的東西......

>>> 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

使用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!'

你也可以嘗試:

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

只要字符串包含至少一個非空格字符,它就會起作用。 我們可以更加小心,然后再檢查一下:

a = '    '
-1 if not a or a.isspace() else a.index(a.lstrip()[0])
=> -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

根據mgilson的回答,您可以使用lstrip去除您想要的任何字符 -

unwanted = ':!@#$%^&*()_+ \t\n'
a= '  _Hello world'
res = len(a) - len(a.lstrip(unwanted)) 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM