更改python中列表中的所有特定字母

时间:2015-03-25 12:33:21

标签: python python-2.7

我想创建一个程序,该程序将一系列字符串作为参数,然后用另一个字母将这些字符串中的每个特定字母用一个字母组合。

例如:

def changeLetter(["test","iteration","123","train"]

我希望这个函数用“T”替换它能找到的每个“t”,并打印该列表。 所以它看起来像这样:

changeLetter(["test","iteration","123","train"]
["TesT","iTeraTion","123,"Train"]

注意!:我不允许使用任何内置函数来完成此任务。但是我可以使用len()和range()

谢谢!

2 个答案:

答案 0 :(得分:0)

你可以这样做,

def changeletter(l):
    m = []
    for i in l:
        s = ""
        for j in i:
            if j == 't':
                j = 'T'
                s += j
            else:
                s += j
        m.append(s)
    print m 
changeletter(["test","iteration","123","train"])

输出:

['TesT', 'iTeraTion', '123', 'Train']

答案 1 :(得分:0)

def changeLetter(item_list):
    result_list = []
    for word in item_list:
        new_word = ''
        for char in word:
            if char == 't':
                new_word += 'T'
            else:
                new_word += char
        result_list.append(new_word)
    print result_list



changeLetter(["test","iteration","123","train"])

您还可以使用字符串函数replace: -

result_list = [word.replace('t', 'T') for word in word_list]