最简单的 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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 21:25:07  来源:igfitidea点击:

simplest python equivalent to R's gsub

pythonrpython-2.7

提问by Deena

Is there a simple/one-line python equivalent to R's gsubfunction?

是否有与 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

gsubis the normal subin python - that is, it does multiple replacements by default.

gsubsub在 python 中是正常的——也就是说,默认情况下它会进行多次替换。

The method signature for re.subis sub(pattern, repl, string, count=0, flags=0)

方法签名re.subsub(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.Iis 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'