最简单的 python 相当于 R 的 gsub
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38773379/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
simplest python equivalent to R's gsub
提问by Deena
Is there a simple/one-line python equivalent to R's gsub
function?
是否有与 Rgsub
函数等效的简单/单行 python ?
strings = c("Important text, !Comment that could be removed", "Other String")
gsub("(,[ ]*!.*)$", "", strings)
# [1] "Important text" "Other String"
回答by Nick Becker
For a 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]
回答by Benjamin Atkin
gsub
is the normal sub
in python - that is, it does multiple replacements by default.
gsub
sub
在 python 中是正常的——也就是说,默认情况下它会进行多次替换。
The method signature for re.sub
is sub(pattern, repl, string, count=0, flags=0)
方法签名re.sub
是sub(pattern, repl, string, count=0, flags=0)
If you want it to do a single replacement you specify count=1
:
如果您希望它执行单个替换,请指定count=1
:
In [2]: re.sub('t', 's', 'butter', count=1)
Out[2]: 'buster'
re.I
is the flag for case insensitivity:
re.I
是不区分大小写的标志:
In [3]: re.sub('here', 'there', 'Here goes', flags=re.I)
Out[3]: 'there goes'
You can pass a function that takes a match object:
您可以传递一个接受匹配对象的函数:
In [13]: re.sub('here', lambda m: m.group().upper(), 'Here goes', flags=re.I)
Out[13]: 'HERE goes'