检测字符串开头的空格字符

时间:2012-07-13 14:03:13

标签: python

如何检测字符串中的空格缩进?

我需要解析一个CSS文件:逐行扫描。 鉴于我有一系列的CSS风格:

strong, b { font-weight: normal; color: #000; }

如何提取该空格并将其保存到变量中?

2 个答案:

答案 0 :(得分:0)

很难说出你想要的是什么,但你可以使用正则表达式轻松地从字符串的开头拉出空格:

import re
def get_whitespace(your_string):
    return re.match(r'\s*',your_string).group()

print len(get_whitespace(' foo')) #1
print len(get_whitespace('bar'))  #0

答案 1 :(得分:0)

您可以从字符串中获取前导空格而不使用正则表达式:

whitespace = string[ : len(string) - len(string.lstrip())]
相关问题