python - 如何轻松检查字符串是否以 4N 个空格开头?

标签 python

如何轻松检查字符串是否以 4*N 空格开头,其中 N 是正整数?

我当前的代码是:

def StartsWith4Nspaces(string):
    count = 0
    for c in string:
        if c == ' ':
            count += 1
        else:
            break
    return count > 0 and count % 4 == 0

是否有更 Pythonic 的方式来写下它?

我有点希望有一个单一的声明(尽管任何比上面更干净的东西都会很棒)。

谢谢。

最佳答案

你可以像这样检查它:

my_string[:4*N] == ' ' * 4*N

您还可以将您的这张支票转换为 lambda:

check = lambda my_string, N: my_string[:4*N] == ' ' * 4*N

并将其命名为:

check('  asdas', 2) # -> True
check('  asdas', 3) # -> False

或者,如果您出于某种原因想要对 N 进行硬编码 (N = 3):

check = lambda my_string: my_string[:12] == ' ' * 12

EDIT: If the 4Nth + 1 character is required to not be a space, you can incorporate that into your lambda:

check_strict = lambda my_string, N: my_string[:4*N] == ' ' * 4*N and my_string[4*N + 1] != ' '

check_strict = lambda my_string: my_string[:12] == ' ' * 12 and my_string[13] != ' '

关于python - 如何轻松检查字符串是否以 4N 个空格开头?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45148499/

相关文章:

python - 我在 NetworkX 图表中看不到标签

python - 我可以将安装在适用于 Linux 的 Windows 子系统上的 Redis 与 Windows 中的 python 应用程序一起使用吗?

python - Openpyxl 创建具有工作表名称和特定单元格值的数据框?

python - 如何减少 PIL 中的 png 图像文件大小

python - 通过另一个数据帧过滤系列/数据帧

python - 列表中的排序列表

python - 如何为 IntegerField 设置 NULL 而不是设置 0?

python - 如何更改 Jupyter Notebook 中的工作目录?

python - 在 python 中,如何限制每个 gvkey 插入虚拟一次?

python - Odoo错误: TypeError: 'int' object is not iterable