社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
私信  •  关注

typedef struct James

typedef struct James 最近创建的主题
typedef struct James 最近回复了
6 年前
回复了 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