simplest python equivalent to R's gsub

你离开我真会死。 提交于 2020-12-29 05:03:24

问题


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"  

回答1:


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]



回答2:


gsub is the normal sub in python - that is, it does multiple replacements by default.

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

If you want it to do a single replacement you specify count=1:

In [2]: re.sub('t', 's', 'butter', count=1)
Out[2]: 'buster'

re.I is the flag for case insensitivity:

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'


来源:https://stackoverflow.com/questions/38773379/simplest-python-equivalent-to-rs-gsub

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!