私信  •  关注

typedef struct James

typedef struct James 最近创建的主题
typedef struct James 最近回复了
7 年前
回复了 typedef struct James 创建的主题 » 如何在python列表中只替换以某个字母开头的文本?

新编辑表示要替换整个单词。只需检查元素 startswith() 所需的字符,然后将其替换为所需的字符串。这会变得有点健壮,所以你可以用字典更好。


for i in range(0, len(list)):
    if list[i].startswith('F'):
        list[i] = 'qwe'
    elif list[i].startswith('H'):
        list[i] = 'equals'
    elif list[i].startswith('S'):
        list[i] = 'chronic'

map = {
    'F': 'qwe',
    'H': 'equals'
    'S': 'chronic'
     # etc etc
}

for i in range(0, len(list)):
    if list[i][0] in map.keys():    # check if first char is a key in map
        list[i] = map[list[i][0]]   # if it is, replace list[i] with the value in map