You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python技术问题:如何将列表中末尾为xy的字符串替换为yx?

Python:替换列表中末尾为"xy"的字符串为"yx"

需求很明确:遍历列表中的每个字符串,仅将末尾是xy的字符串替换为末尾yx,其余字符串保持不变。

示例输入输出

输入列表:

original_list = ["asdxy", "abcyx", "asd"]

期望输出列表:

['asdyx', 'abcyx', 'asd']

解决方案

方法一:列表推导式(简洁高效)

这是Python处理这类问题最常用的方式,一行代码就能完成:

original_list = ["asdxy", "abcyx", "asd"]
result_list = [s[:-2] + "yx" if s.endswith("xy") else s for s in original_list]
print(result_list)

逻辑说明:

  • s.endswith("xy"):检查当前字符串是否以xy结尾
  • 满足条件时,用s[:-2]截取字符串除最后两位外的部分,再拼接yx
  • 不满足条件则直接保留原字符串

方法二:循环遍历(适合新手理解)

如果觉得列表推导式不够直观,也可以用普通循环逐个处理:

original_list = ["asdxy", "abcyx", "asd"]
result_list = []
for s in original_list:
    if len(s) >= 2 and s.endswith("xy"):  # 加长度判断更严谨,避免短字符串无意义判断
        new_str = s[:-2] + "yx"
        result_list.append(new_str)
    else:
        result_list.append(s)
print(result_list)

内容的提问来源于stack exchange,提问作者Stewestrong

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 09:20:39