Python将嵌套列表中的单词首字母大写

时间:2015-08-03 04:13:35

标签: python string python-2.7

使用python 2.7

如何编写一个函数来大写字符串的第一个字母而不管其余部分(即不使用.capitalize())然后使用另一个以嵌套列表作为参数的函数,应用第一个函数在嵌套的for循环中?
例如

def capital_first():
   #some code

def capital_nested([['heLLo','hi'],['giddAy'',goodday'],['gooDbye,'seeYA','adios']])
   #some code
   capital_first()

输出另一个带有大写字母的嵌套列表

[['HeLLo','Hi'],['GiddAy'',Goodday'],['GooDbye,'SeeYA','Adios']]

我目前有

def cap_first(word):
    newone = word[0].upper()
    return newone

def capitalize_nested(x):
    newlist = []
    for item in x:
        for word in item:
            newlist.append(cap_first(word))
    print newlist

输出

['M', 'M', 'Y', 'Y', 'T', 'T', 'T']

我知道这是因为我已将word[0]编入索引但不确定如何解决此问题。

2 个答案:

答案 0 :(得分:2)

您需要在循环中重新创建内部列表:

def capitalize_nested(x):
    newlist = []
    for item in x:
        newlist2 = []
        for word in item:
            newlist2.append(cap_first(word))
        newlist.append(newlist2)
    print newlist

答案 1 :(得分:1)

newone = word[0].upper()

有了这个,这个词的其余部分就被丢弃了。相反,像这样追加其余部分:

newone = word[0].upper() + word[1:]
相关问题