2014-01-19 51 views
-5

下面的代碼大寫了「w」中單詞的第一個單詞。我想知道函數captilize(句子)是如何工作的?具體來說,sentence.split是做什麼的?使用python代碼對一個句子中第一個字母的大寫字母

`

import random 

def test(): 
    w = ["dog", "cat", "cow", "sheep", "moose", "bear", "mouse", "fox", "elephant", "rhino", "python"] 
    s = "" 

    #random.seed(rnd_seed) 

    for i in range(0, random.randint(10,15)): 
    s += random.choice(w) + " " 
    print "<ignore>Sentence: " + s 
    print "Capitalized: " + capitalize(s).strip() 


def capitalize(sentence): 
    w = sentence.split() 
    ww = "" 
    for word in w: 
    ww += word.capitalize() + " " 
    return ww 


test()` 
+0

在一個交互式Python提示符,嘗試'幫助(「」分割)' –

+0

你永遠不會了解,如果你不嘗試。這個問題必須關閉,因爲它沒有顯示對代碼的最小理解。 –

+0

正如@Anonymous所說,你自己做點什麼,就像在你的Python提示符中嘗試幫助命令一樣。 –

回答

0

.split(SEP): 具體分裂方法以一個字符串並返回的詞的列表字符串中,使用月作爲分隔符串。如果沒有分隔符值被傳遞,則將空格作爲分隔符。

例如:

a = "This is an example" 
a.split()  # gives ['This', 'is', 'an', 'example'] -> same as a.split(' ') 

談論你的功能,它需要一個字符串形式的句子,每個單詞大寫返回的句子。讓我們來看看它逐行:

def capitalize(sentence): # sentence is a string 
    w = sentence.split()  # splits sentence into words eg. "hi there" to ['hi', there'] 
    ww = ""     # initializes new string to empty 
    for word in w:     # loops over the list w 
    ww += word.capitalize() + " "  # and capitalizes each word and adds to new list ww 
    return ww        # returns the new list 
相關問題