如何拆分字符串中的姓名并剔除指定单词「and」
字符串拆分操作实现
需求说明
原始待处理字符串:"Oscar Wilde, Sophocles, and Lin-Manuel Miranda"
预期输出结果(剔除单词and后的列表):["Oscar Wilde", "Sophocles", "Lin-Manuel Miranda"]
实现方法(Python示例)
方法1:分割后过滤
先按逗号分割字符串,再遍历清理每个元素的多余空格,过滤掉值为and的项:
original_str = "Oscar Wilde, Sophocles, and Lin-Manuel Miranda" result = [item.strip() for item in original_str.split(',') if item.strip() != 'and']
运行后result即为目标列表。
方法2:替换指定内容后直接分割
先把字符串里多余的, and 替换为普通逗号,再直接按逗号分割:
original_str = "Oscar Wilde, Sophocles, and Lin-Manuel Miranda" result = original_str.replace(', and ', ',').split(',')
内容的提问来源于stack exchange,提问作者SEUN
相关产品推荐
相关产品推荐

