2017-07-17 84 views
4

如何輕鬆檢查字符串是否以4*N空格開頭,其中N是一個正整數?如何輕鬆檢查一個字符串是否以4N空格開頭?

我當前的代碼是:

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

有沒有寫下來一個更Python的方式?

我有點希望得到一個單一的聲明(雖然比上述任何更乾淨的將是偉大的)。

謝謝。

+1

以'4 * N + 1'開頭的字符串是否符合您以'4 * N'開頭的要求?就像你在字符串開頭的空格的數量是* * * * * * * * * * * * *一樣,或者只是以'4 * N'空格開始的字符串。 –

回答

4

您可以只檢查它像這樣:

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 

編輯:如果第4n個+ 1個字符需要是一個空間,你可以結合到你的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] != ' ' 
+0

需要一個參數'N'。 OP似乎想要這樣做沒有這個參數 – inspectorG4dget

+0

是否有一個特定的原因,你選擇索引切片,而不是'str.startswith()'?這看起來像'startswith()'的確切用例是專爲...... –

+0

也是這個答案是錯誤的 - 在OP的問題中的代碼要求「計數%4 == 0」,即*正好*'4 * N'空格是必需的,沒有更多。 –

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

可以使用lstrip方法剝離開始空白,然後比較剝離和原始字符串的長度:

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

(你甚至可以通過不設置變量一行使它秒。)

+0

酷!謝謝! – goodvibration

+2

雖然lstrip可能更好,但是... – goodvibration

+0

@goodvibration謝謝,修正了 –

0

假設你只想要正好 N個空格 - 不多不少於 - 在字符串的開頭,然後使用正則表達式;

import re  
def starts_with_four_n_spaces(eval_string): 
    return re.search(r'^(?:\s{4})+(?!\s).*$', eval_string) is not None 

輸出;

>>> starts_with_four_n_spaces(' foo') 
False 
>>> starts_with_four_n_spaces('  foo') 
True 

圖案^(?:\s{4})+(?!\s).*$工作如下

  • ^(?:\s{4})+匹配的四個空間的倍數;
  • (?!\s)斷言這不是跟着另一個空間;
  • .*$匹配任何東西直到字符串結束。
1

有很多選擇。請注意,您可以「切分」一個字符串以獲取前四個字符。然後你可以將它與空格進行比較。這裏有一個例子:

mystring[:4] == ' ' 

您也可以使用字符串的startswith功能:

mystring.startswith(' ') 

注意,如果字符串有5個或多個空格開始,這兩種方法仍然會返回True。如果您需要找到起始空格的方法,則正則表達式可能更適合。

如果空格的個數可以是一個變量,只需使用' '*N其中N是要匹配的空格數。

+0

我很確定startswith()比其他解決方案(尤其是使用reg ex)的性能更好。 –

+0

任何收益與正則表達式都將通過迭代找到N並確保沒有任何收益而被咀嚼。開始時有6個空格。 –

+0

好點。我會注意到這些方法並不考慮當超過4個空格時會發生什麼情況。 – SNygard

1

你可以做到這一點通過以下方式

def StartsWith4Nspaces(s): 
    diff = len(s) - len(s.lstrip(' ')) 
    return ((diff > 0) and not (diff%4)) 

print(StartsWith4Nspaces('abc')) 
print(StartsWith4Nspaces(' ' * 1 + 'abc')) 
print(StartsWith4Nspaces(' ' * 4 + 'abc')) 
print(StartsWith4Nspaces(' ' * 6 + 'abc')) 
print(StartsWith4Nspaces(' ' * 8 + 'abc')) 

輸出

False 
False 
True 
False 
True 

基本上你刪除前導空格和長度比較差的剝離和原始字符串。

2

使用正則表達式工作體面此:

>>> 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,並與只包含空格的字符串工作。一個有效的匹配被認爲是真實的,但是如果你想要它是一個嚴格的bool,你可以將結果傳遞給bool()。用+更換*將迫使N到大於0

0

另一個正則表達式的答案:

re.search('[^ ]', string).start() % 4 == 0

查找第一個非空格字符和modulos w.r.t.的索引4。

或者與列表理解相同的方法:

next(i for i, c in enumerate(string) if c != ' ') % 4 == 0

0

可以slice字符串,並使用all()內置的方法來檢查切片string是你所需要的,如下:

st = ' testString' 
N = 1 
print all(x == ' ' for x in st[:4*N]) 

將輸出

True 
相關問題