检查字符串缩进?

编程入门 行业动态 更新时间:2024-10-11 07:32:11
本文介绍了检查字符串缩进?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在为一系列字符串构建分析器. 我需要检查每行缩进了多少(通过制表符或空格).

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]

更多推荐

检查字符串缩进?

本文发布于:2023-11-12 13:31:09,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1581639.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!