问题描述
我正在为一系列字符串构建分析器.我需要检查每行缩进了多少(通过制表符或空格).
I'm building an analyzer for a series of strings.I need to check how much each line is indented (either by tabs or by spaces).
每一行只是文本编辑器中的一个字符串.如何检查缩进多少字符串?
Each line is just a string in a text editor.How do I check by how much a string is indented?
或者,也许我可以检查字符串前有多少空格或\ t,但是我不确定如何.
Or rather, maybe I could check how much whitespace or \t are before a string, but I'm unsure of how.
推荐答案
要计算字符串开头的空格数,您可以在左剥离(除去空格)的字符串与原始字符串之间进行比较:
To count the number of spaces at the beginning of a string you could do a comparison between the left stripped (whitespace removed) string and the original:
a = " indented string"
leading_spaces = len(a) - len(a.lstrip())
print(leading_spaces)
# >>> 4
制表符缩进是特定于上下文的...它会根据显示制表符的任何程序的设置而变化.这种方法只会告诉您空白字符的总数(每个选项卡将被视为一个字符).
Tab indent is context specific... it changes based on the settings of whatever program is displaying the tab characters. This approach will only tell you the total number of whitespace characters (each tab will be considered one character).
或演示:
a = "\t\tindented string"
leading_spaces = len(a) - len(a.lstrip())
print(leading_spaces)
# >>> 2
如果要对整个文件执行此操作,则可能要尝试
If you want to do this to a whole file you might want to try
with open("myfile.txt") as afile:
line_lengths = [len(line) - len(line.lstrip()) for line in afile]
这篇关于检查字符串缩进?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!