Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I easily check if a string starts with 4N spaces?

Tags:

python

How can I easily check if a string starts with 4*N spaces, where N is a positive integer?

My current code is:

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

Is there a more Pythonic way to write this down?

I'm kinda hoping for a single statement (though anything cleaner than the above would be great).

Thank you.

like image 955
goodvibration Avatar asked Jul 17 '17 15:07

goodvibration


People also ask

How do you check if a string starts with space?

Check If String Starts with Space using RegEXP and match() The regular expression /^\s/ is passed as an argument to the match() method . / and / specify the start and end of expression. ^ specifies the beginning character. If the first character is a space from the pattern, the matching expression is returned.

How do you check if a space is in a string python?

Python String isspace() The isspace() method returns True if there are only whitespace characters in the string. If not, it return False. Characters that are used for spacing are called whitespace characters.

How do you check if there is a space in a string Javascript?

Use the test() method to check if a string contains whitespace, e.g. /\s/. test(str) . The test method will return true if the string contains at least one whitespace character and false otherwise.

How do I check if a string contains only space in flutter?

You can do this by simply using trim. var str = " "; if (str. trim(). length == 0) { console.


4 Answers

You can just check for it like so:

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

You can also convert this check of yours into a lambda:

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

and call it as:

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

Or if you want to hardcode the N for whatever reason (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] != ' '

or

check_strict = lambda my_string: my_string[:12] == ' ' * 12 and my_string[13] != ' '
like image 123
Ma0 Avatar answered Oct 21 '22 01:10

Ma0


Using a regular expression works decently for this:

>>> 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>

Note that this will allow N to be 0, and works with strings that only contain spaces. A valid match is considered true, but you can pass the result to bool() if you want it to be strictly a bool. Replacing the * with a + will force N to be greater than 0.

like image 38
Ignacio Vazquez-Abrams Avatar answered Oct 20 '22 23:10

Ignacio Vazquez-Abrams


You can use the lstrip method to strip starting whitespace and then compare the lengths of the stripped and original strings:

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

(You could even make it one line by not setting a variable for s.)

like image 34
Cary Shindell Avatar answered Oct 21 '22 00:10

Cary Shindell


def startsWith4Nspaces(s):
    if not s: return False

    numLeadingSpaces = len(s) - len(s.lstrip(' '))
    if not numLeadingSpaces: return False
    if numLeadingSpaces%4: return False
    return True
like image 35
inspectorG4dget Avatar answered Oct 20 '22 23:10

inspectorG4dget