Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

simplest python equivalent to R's 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"   
like image 838
Deena Avatar asked Aug 04 '16 17:08

Deena


People also ask

What is gsub python?

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)

How do you're sub in Python?

If you want to replace a string that matches a regular expression (regex) instead of perfect match, use the sub() of the re module. In re. sub() , specify a regex pattern in the first argument, a new string in the second, and a string to be processed in the third.


1 Answers

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] 
like image 199
Nick Becker Avatar answered Sep 20 '22 12:09

Nick Becker