使用 Python 只保留字符串中的某些字符? [英] Keeping only certain characters in a string using Python?

查看:38
本文介绍了使用 Python 只保留字符串中的某些字符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的程序中,我有一个这样的字符串:

In my program I have a string like this:

ag ct oso gcota

ag ct oso gcota

使用 python,我的目标是去掉空格并只保留 a、t、c 和 g 字符.我了解如何摆脱空白(我只是使用 line = line.replace(" ", "")).但是,当我不需要的字符可能是字母表中的任何其他字母时,我该如何摆脱它们呢?

Using python, my goal is to get rid of the white space and keep only the a,t,c,and g characters. I understand how to get rid of the white space (I'm just using line = line.replace(" ", "")). But how can I get rid of the characters that I don't need when they could be any other letter in the alphabet?

推荐答案

一个非常优雅和快速的方法是使用正则表达式:

A very elegant and fast way is to use regular expressions:

import re

str = 'ag ct oso gcota'
str = re.sub('[^atcg]', '', str)

"""str is now 'agctgcta"""

这篇关于使用 Python 只保留字符串中的某些字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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