python - 使用 Python 只保留字符串中的某些字符?

标签 python string replace

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

g ct oso gcota

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

最佳答案

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

import re

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

"""str is now 'agctgcta"""

关于python - 使用 Python 只保留字符串中的某些字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15754587/

相关文章:

python - 如何使用 python 挂载 USB 设备或硬盘分区

python - 为什么 python 在我的字符串中的单引号之前添加 "\\"

string - 如何在 XQuery 中的一定数量的字符串字符后插入字符串?

javascript - 将符号编号替换为 gif

string - Lua 字符串替换

python - numpy : find number of active tickets at time t given a list of start and duration

python - 指定 eventlet wsgi 服务器的进程数

java - 如何在java中翻译带有不可打印字符的字符串

python - 拆分字符串并生成键值对

php - MySQL:删除部分字符串,直到倒数第三个出现的正斜杠