返回Python中字符串中第一个非空白字符的最低索引

Pab*_*blo 9 python string string-matching

在Python中执行此操作的最短方法是什么?

string = "   xyz"
Run Code Online (Sandbox Code Playgroud)

必须返回index = 3

Fra*_*ank 34

>>> s = "   xyz"
>>> len(s) - len(s.lstrip())
3
Run Code Online (Sandbox Code Playgroud)

  • 如果s很长并且空白前缀很短,那么其他解决方案(那些不会使s几乎复制s,得到它的长度,然后抛出临时对象的解决方案)可能更好. (2认同)

Sil*_*ost 6

>>> next(i for i, j in enumerate('   xyz') if j.strip())
3
Run Code Online (Sandbox Code Playgroud)

要么

>>> next(i for i, j in enumerate('   xyz') if j not in string.whitespace)
3
Run Code Online (Sandbox Code Playgroud)

在Python <2.5的版本中你必须这样做:

(...).next()
Run Code Online (Sandbox Code Playgroud)