Python程式列印字串中偶數長度的單詞


在Python程式語言中,長度是指計算字串的整個範圍,從字串的第一個字元到最後一個字元。列印和計算字串中的偶數長度是一個基本的程式設計練習。

在本教程中,我們將學習如何找到字串中所有長度為偶數的單詞。如果一個數字能被2整除,即餘數為0,則認為它是偶數。這個屬性應該適用於我們需要單詞的長度。因此,程式的目標是隻列印長度為偶數的單詞,並跳過所有不滿足上述屬性的單詞。

例如,如果我們有一個單詞字串“A big cube was found inside the box.”,對於這個字串,我們的程式應該只打印單詞:“cube”和“inside”,因為這些單詞的長度分別為4和6。

方法

  • 使用str.split()函式將字串分割成單詞。

  • 遍歷單詞。

  • 使用len()函式計算單詞的長度。

  • 如果長度為偶數,則列印單詞。

  • 否則什麼也不做。

str.split()

這是適用於python字串的內建函式。此函式的作用是根據指定的分割符(如果沒有指定分割符,則為空格)分割字串函式。

在Python直譯器中,以下函式的幫助資訊如下所示:

split(self, /, sep=None, maxsplit=-1) Return a list of the words in the string, using ‘sep’ as the delimiter string. sep The delimiter according which to split the string. None (the default value) means split according to any whitespace, and discard empty strings from the result. maxsplit Maximum number of splits to do. -1 (the default value) means no limit.

len()

Len是python中最常用的函式,用於計算python中任何資料物件的字元或元素數量。例如,對於字串“aaa”,len(“aaa”)將返回3。

來自Python直譯器的內建幫助:

len(obj, /)
   Return the number of items in a container.
For a string, its wrapper str.__len__() is called.

示例

在下面的示例中,我們實現了上述方法。我們建立了一個函式,用於從字串中過濾出所有長度為偶數的單詞。

def printEvenLengthWords(s): # splitting the words in a given string words = s.split() # same as s.split(' ') for word in words: # checking the length of words if len(word) % 2 == 0: print(word) # input string sample = 'this is a test string' # calling the function printEvenLengthWords(sample)

輸出

this
is      
test    
string

一點Python額外內容

Python包含一個名為filter()的內建函式,它返回一個迭代器。

它接受兩個引數,第一個是布林函式,第二個是應該應用它的可迭代物件。我們可以將上述任何方法用作此函式。

使用filter()時必須特別注意,因為它是可以耗盡的,這意味著一旦它被用於遍歷或轉換為列表,如果再次遍歷,它將返回None,因此最好將其轉換為列表並存儲在另一個變數中。

語法

evenWords = filter(lambda x: len(x) % 2 == 0, 'this is a test string'.split())

示例

def printEvenLengthWords(s): # splitting the words in a given string words = s.split() # same as s.split(' ') # checking the length of words evenWords = filter(lambda x: len(x) % 2 == 0, words) for word in evenWords: print(word) # calling the function with input string passed in directly printEvenLengthWords('this is a test string')

輸出

this
is      
test    
string

在上面的示例中,lambda函式’x’的引數代替了split函式返回的每個元素。它的作用很像for迴圈,但它是python的簡寫方式。

使用filter()和列表推導的Python單行程式碼

我們可以直接在filter物件上呼叫print(),並設定可選引數’sep’為’\n’或換行符。開頭的’*’表示解包可迭代物件並列印所有內容,分隔符將它們在新行中打印出來。可以按如下方式進行。

使用Lambda

def printEvenLengthWords(s): # please note that one liners are hard to understand # and may be frowned upon in some cases print(*filter(lambda x: len(x) % 2 == 0, s.split()), sep='\n')

使用列表推導式

def printEvenLengthWords(s): print(*[x for x in s.split() if len(x) % 2 == 0], sep='\n') # input string sample = 'this is a test string' # calling the function printEvenLengthWords(sample)

輸出

this
is      
test    
string

注意

當使用帶有以句點(.)結尾的多個語句的split()函式時,它也會與最後一個單詞一起計數。

示例

x = 'Example statement 1. Some line 2.'

當將上述字串傳遞給函式時,它還將包含“1.”和“2.”。

輸出

1.
Some    
line    
2.

可以透過一個簡單的技巧來解決這個問題。我們可以使用replace()呼叫刪除所有句點,如下所示:

x = 'Example statement 1. Some line 2.'
x = x.replace('.', '')

示例

def printEvenLengthWords(s): # handle full stops s = s.replace('.', '') # splitting the words in a given string words = s.split() # same as s.split(' ') for word in words: # checking the length of words if len(word) % 2 == 0: print(word) # input string sample = 'Example statement 1. Some line 2.' # calling the function printEvenLengthWords(sample)

輸出

Some    
line

但是需要注意的是,它甚至會刪除句子中間的句點,對於更強大的替代方案,可以使用正則表示式模式。

正則表示式模式

示例

\w\.(\s[A-Z])?

這檢查是否有任何單詞字元後跟一個句點,然後是字串終止或新句子以大寫字母開頭。可以在其他教程中更深入地學習正則表示式。

更新於:2022年10月13日

6000+ 瀏覽量

啟動你的職業生涯

透過完成課程獲得認證

開始學習
廣告