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"
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 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.
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With