最简单的 python 相当于 R 的 gsub [英] simplest python equivalent to R's gsub
本文介绍了最简单的 python 相当于 R 的 gsub的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否有一个简单的/一行 Python 等价于 R 的 gsub
函数?
Is there a simple/one-line python equivalent to R's gsub
function?
strings = c("Important text, !Comment that could be removed", "Other String")
gsub("(,[ ]*!.*)$", "", strings)
# [1] "Important text" "Other String"
推荐答案
对于字符串:
import re
string = "Important text, !Comment that could be removed"
re.sub("(,[ ]*!.*)$", "", string)
由于您将问题更新为字符串列表,因此您可以使用列表推导式.
Since you updated your question to be a list of strings, you can use a list comprehension.
import re
strings = ["Important text, !Comment that could be removed", "Other String"]
[re.sub("(,[ ]*!.*)$", "", x) for x in strings]
这篇关于最简单的 python 相当于 R 的 gsub的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文