计算字符串中前导空格的pythonic方法是什么? [英] What is the pythonic way to count the leading spaces in a string?

查看:64
本文介绍了计算字符串中前导空格的pythonic方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道我可以用这个来计算字符串中的前导空格:

<预><代码>>>>a = " foo bar baz qua \n">>>打印前导空格",len(a) - len(a.lstrip())前导空格 3>>>

但是有没有更pythonic的方法?

解决方案

你的方式是 pythonic 但不正确,它也会计算其他空白字符,只计算空格是显式的 a.lstrip(' '):

a = " \r\t\n\tfoo bar baz qua \n"打印前导空格",len(a) - len(a.lstrip())>>>前导空格 7打印前导空格",len(a) - len(a.lstrip(' '))>>>前导空格 3

I know I can count the leading spaces in a string with this:

>>> a = "   foo bar baz qua   \n"
>>> print "Leading spaces", len(a) - len(a.lstrip())
Leading spaces 3
>>>

But is there a more pythonic way?

解决方案

Your way is pythonic but incorrect, it will also count other whitespace chars, to count only spaces be explicit a.lstrip(' '):

a = "   \r\t\n\tfoo bar baz qua   \n"
print "Leading spaces", len(a) - len(a.lstrip())
>>> Leading spaces 7
print "Leading spaces", len(a) - len(a.lstrip(' '))
>>> Leading spaces 3

这篇关于计算字符串中前导空格的pythonic方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆