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

2024-10-03 05:24:16 发布

您现在位置: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

有没有一种更像Python的方式来写下来?在

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

谢谢。在


Tags: and字符串代码inforstringreturnif
3条回答

你可以这样检查:

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

您也可以将您的支票转换为lambda

^{pr2}$

称之为:

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] != ' '

可以使用lstrip方法去除起始空格,然后比较剥离字符串和原始字符串的长度:

s = string.lstrip()
return ((len(string) - len(s)) % 4 == 0 and (len(string) - len(s) != 0)

(您甚至可以通过不为s设置变量使其成为一行。)

为此,使用正则表达式非常合适:

>>> re.match('(?: {4})*(?! )', '')
<_sre.SRE_Match object at 0x7fef988e4780>
>>> re.match('(?: {4})*(?! )', '  ')
>>> re.match('(?: {4})*(?! )', '    ')
<_sre.SRE_Match object at 0x7fef988e4718>
>>> re.match('(?: {4})*(?! )', 'foo')
<_sre.SRE_Match object at 0x7fef988e4780>
>>> re.match('(?: {4})*(?! )', '  foo')
>>> re.match('(?: {4})*(?! )', '    foo')
<_sre.SRE_Match object at 0x7fef988e4718>
>>> re.match('(?: {4})*(?! )', '      foo')
>>> re.match('(?: {4})*(?! )', '        foo')
<_sre.SRE_Match object at 0x7fef988e4780>

请注意,这将允许N为0,并且可以处理只包含空格的字符串。有效匹配被认为是true,但是如果您希望结果严格地是bool,那么可以将结果传递给bool()。将*替换为+将强制N大于0。在

相关问题 更多 >