python:仅在此列表内时保留char [英] python: keep char only if it is within this list

查看:68
本文介绍了python:仅在此列表内时保留char的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个列表:

a = ['a','b','c'.........'A','B','C'.........'Z']

我有一个字符串:

string1= 's#$%ERGdfhliisgdfjkskjdfW$JWLI3590823r'

我只想保留a

最有效的方法是什么?也许不是让a成为列表,我应该将其设为字符串?像这样a='abcdefg..........ABC..Z' ??

what is the most effecient way to do this? perhaps instead of having a be a list, i should just make it a string? like this a='abcdefg..........ABC..Z' ??

推荐答案

''.join([s for s in string1 if s in a])

说明:

[s for s in string1 if s in a]

创建一个字符串1中所有字符的列表,但前提是它们也位于列表a中.

creates a list of all characters in string1, but only if they are also in the list a.

''.join([...])

通过在给定列表的元素之间不添加任何字符('')将其转换为字符串.

turns it back into a string by joining it with nothing ('') in between the elements of the given list.

这篇关于python:仅在此列表内时保留char的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆