且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

检查字符串缩进?

更新时间:2023-09-03 16:28:22

要计算字符串开头的空格数,您可以在左剥离(除去空格)的字符串与原始字符串之间进行比较:

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]